用java将文件附加到电子邮件
我想知道我做错了什么(我错过了什么)。我的电子邮件确实发送出去了,但没有附件。我正在发送的文件称为“日志”。正如您将看到的,我在这里尝试了多种方法,我也一个接一个地尝试了这些方法,但没有一种有效:用java将文件附加到电子邮件,java,file,attachment,Java,File,Attachment,我想知道我做错了什么(我错过了什么)。我的电子邮件确实发送出去了,但没有附件。我正在发送的文件称为“日志”。正如您将看到的,我在这里尝试了多种方法,我也一个接一个地尝试了这些方法,但没有一种有效: MimeMessage message = new MimeMessage(session); MimeBodyPart emailAttachment = new MimeBodyPart(); Multipart multip
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();
}
}
}
这可能有助于您确定所引用的文件是否存在并包含内容?除此之外,您的代码看起来还不错。我认为您应该尝试调试并逐行检查send方法。我确实通过尝试捕获文件是否为null来验证该文件是否存在。它不是空的。我可以手动转到该目录并找到名为log的文件。它有上下文,但没有文件扩展名。它没有文件扩展名这一事实会有所不同吗?