[英]Attaching file to email in java
我想知道我在這里做錯了什么(我想念的是什么)。 我的電子郵件確實發送了,但是沒有附件。 我發送的文件簡稱為“ log”。 如您所見,我在這里嘗試了多種方法,我也一步一步地嘗試了它們,但是它們都不起作用:
MimeMessage message = new MimeMessage(session);
MimeBodyPart emailAttachment = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
int len = build.getLogFile().getPath().length();
//I have verified that "file" provides the right path
String file = build.getLogFile().getPath().substring(0, (len-3));
String fileName = "log";
DataSource source = new FileDataSource(file);
emailAttachment.setDataHandler(new DataHandler(source));
//I know this .attachFile is not needed but I added it when nothing was working
emailAttachment.attachFile(build.getLogFile());
emailAttachment.setFileName(fileName);
multipart.addBodyPart(emailAttachment);
message.setContent(multipart);
message.setFrom(adminAddress);
message.setText(builder.toString());
message.setSentDate(new Date());
mailSender.send(message);
謝謝
使用此代碼=>
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendFileEmail
{
public static void main(String [] args)
{
String to = "abcd@gmail.com";
String from = "web@gmail.com";
String host = "localhost";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("This is the Subject Line!");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("This is message body");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
String filename = "file.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart );
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.