jakarta mail Java发送附件中包含文件的电子邮件
我想用java发送附件中的文件。 我有两个类,一个是指定文件位置的类,另一个是用作发送电子邮件的实用程序类 因此,当我执行第一个类时,它不会发送电子邮件
头等舱:
public class SendFile {
private static String[] args;
public static void sendEmail(File filetosend) throws IOException, Exception{
//public static void main(String[] args) throws IOException {
final String username = "email0@gmail.com";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", true);
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("email0@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("email0@gmail.com"));
message.setSubject("Attach file Test from Netbeans");
message.setText("PFA");
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
//String filetosend = ("c:\\file.txt");
DataSource source = new FileDataSource(filetosend);
System.out.println("The filetosend is ="+filetosend);
messageBodyPart.setDataHandler(new DataHandler(source));
System.out.println("The source is ="+source);
messageBodyPart.attachFile(filetosend);
System.out.println("The file name is ="+messageBodyPart.getFileName());
multipart.addBodyPart(messageBodyPart);
System.out.println("The message body part is ="+messageBodyPart);
message.setContent(multipart);
System.out.println("The message multi part is ="+multipart);
System.out.println("Sending");
Transport.send(message);
System.out.println("The message is ="+message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
第二类:
import java.io.File;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws Exception {
}
File file;
public void Test() throws IOException, Exception{
System.out.println("Sending the file...");
File filetosend = new File("c:\\file.txt");
SendFile.sendEmail(filetosend);
}
}
没有错误,但文件未发送。 请帮忙,谢谢
# 1 楼答案
你的代码看起来不错。事实上,我使用几乎完全相同的代码发送带有附件的邮件。您可能应该考虑是否需要使用主机、端口、身份验证id和身份验证过程向传输和连接添加身份验证。另外,检查是否有防火墙阻止带有附件的邮件(这是一个非常常见的问题)
如果你看这篇文章Stack Overflow post on sending multiple attachments
您将看到几乎完成了相同的操作,并给出了一个如何使用身份验证发送消息的示例
# 2 楼答案
你的代码错了。如果你从某个地方复制了它,那么原稿也错了,或者你复制了它。这就是你想要的: