在此示例中,我们创建了一个小程序来发送带有文件附件的电子邮件。要发送带有附件的消息,我们需要创建一个javax.mail.Multipart对象为电子邮件的对象,该对象基本上将包含电子邮件文本消息,然后将文件添加到第二个块中,这两个对象都是的对象javax.mail.internet.MimeBodyPart。在此示例中,我们还使用javax.activation.FileDataSource。
package org.nhooo.example.mail;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Date;
import java.util.Properties;
public class SendEmailWithAttachment {
public static void main(String[] args) {
SendEmailWithAttachment demo = new SendEmailWithAttachment();
demo.sendEmail();
}
public void sendEmail() {
// 定义电子邮件信息。
String from = "nhooo@gmail.com";
String to = "nhooo@gmail.com";
String subject = "Important Message";
String bodyText = "This is a important message with attachment.";
// 附件文件名。
String attachmentName = "D:/Temp/hello.txt";
// 创建具有以下属性的会话。
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "587");
Session session = Session.getDefaultInstance(props);
try {
InternetAddress fromAddress = new InternetAddress(from);
InternetAddress toAddress = new InternetAddress(to);
// 创建一个Internet邮件味精。
MimeMessage msg = new MimeMessage(session);
msg.setFrom(fromAddress);
msg.setRecipient(Message.RecipientType.TO, toAddress);
msg.setSubject(subject);
msg.setSentDate(new Date());
// 设置电子邮件信息文本。
MimeBodyPart messagePart = new MimeBodyPart();
messagePart.setText(bodyText);
// 设置电子邮件附件文件
FileDataSource fileDataSource = new FileDataSource(attachmentName);
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.setDataHandler(new DataHandler(fileDataSource));
attachmentPart.setFileName(fileDataSource.getName());
// 创建多部分电子邮件。
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messagePart);
multipart.addBodyPart(attachmentPart);
msg.setContent(multipart);
//发送信息。不要忘记设置用户名和密码
// 验证邮件服务器。
Transport.send(msg, "nhooo", "********");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}Maven依赖
<!-- http://repo1.maven.org/maven2/javax/mail/javax.mail-api/1.5.6/javax.mail-api-1.5.6.jar --> <dependency> <groupId>javax.mail</groupId> <artifactId>javax.mail-api</artifactId> <version>1.5.6</version> </dependency> <!-- http://repo1.maven.org/maven2/javax/mail/mail/1.4.7/mail-1.4.7.jar --> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency>