本文将介绍带附件的邮件发送,因为在上文中较详细的说明了一些关键代码作用;
在此就不重复,对代码略作简化,只说明附件部分的代码。
下面直接上代码:
package com.company;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Date;
import java.util.Properties;
/**
* Created by lining on 2018/5/26.
*/
public class AttachMessageSender {
private static final String nickname = "李宁";
private static final String username = "152****1370@163.com";
private static final String password = "******";
private static final String protocol = "smtp";
private static final String host = "smtp.163.com";
private static final String port = "25";
public static void main(String[] args) {
String to = "******9997@qq.com;******9267@163.com";
String subject = "文本邮件主题";
String body = "文本邮件内容";
String attach = "D:\\TXT\\CMD命令.txt;D:\\TXT\\常用MYSQL语句.txt";
Email email = new Email();
email.setToEmails(to.split(";"));
email.setSubject(subject);
email.setContent(body);
email.setAttachments(attach.split(";"));
if (sendEmail(email)) {
System.out.println("邮件发送成功!");
} else {
System.out.println("邮件发送失败!请及时解决!");
}
}
/**
* 发送邮件
* @param email 邮件信息实体
* @return 是否发送成功 TRUE 发送成功 FALSE 发送失败
*/
public static boolean sendEmail(Email email) {
try {
// 创建Session实例对象
Session session = createSession();
// 创建MimeMessage实例对象
MimeMessage message =createMessage(session, email);
// 发送邮件
System.out.println("发送邮件中......");
Transport.send(message);
return true;
} catch (Exception e) {
System.out.println("发送邮件异常==》");
e.printStackTrace();
return false;
} finally {
System.out.println("邮件发送结束...");
}
}
/**
* 创建与邮件服务器的会话对象
* @return 服务器的会话对象
*/
public static Session createSession() {
// 封装属性参数
Properties props = new Properties();
props.setProperty("mail.transport.protocol", protocol);
props.setProperty("mail.smtp.host", host);
props.setProperty("mail.smtp.port", port);
props.setProperty("mail.smtp.auth", "true"); // 是否需要验证设置为TRUE,使用授权码发送邮件需要验证
// 获取与服务器的会话Session对象
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 登陆账号及密码,密码需要是第三方授权码
return new PasswordAuthentication(username, password);
}
});
return session;
}
/**
* 创建邮件的核心内容
* @param session 与服务器交互的会话对象
* @param email 邮件实体
* @return 生成的MimeMessage实例对象
* @throws Exception
*/
public static MimeMessage createMessage(Session session, Email email) throws Exception{
// 创建MimeMessage实例对象:表示一整封邮件
MimeMessage message = new MimeMessage(session);
// 设置发件人
if (!nickname.isEmpty()) {
// 自定义发件人昵称
message.setFrom(new InternetAddress(MimeUtility.encodeText(nickname) + " <" + username + ">"));
} else {
message.setFrom(new InternetAddress(username));
}
// 设置收件人
String[] toEmails = email.getToEmails();
if (toEmails != null && toEmails.length != 0) {
InternetAddress[] internetAddressTO = new InternetAddress[toEmails.length];
for (int i = 0; i < toEmails.length; i++) {
internetAddressTO[i] = new InternetAddress(toEmails[i]);
}
message.setRecipients(Message.RecipientType.TO, internetAddressTO);
}
// 设置密送人
String[] bccEmails = email.getBccEmails();
if (bccEmails != null && bccEmails.length != 0) {
InternetAddress[] internetAddressBCC = new InternetAddress[bccEmails.length];
for (int i = 0; i < bccEmails.length; i++) {
internetAddressBCC[i] = new InternetAddress(bccEmails[i]);
}
message.setRecipients(Message.RecipientType.BCC, internetAddressBCC);
}
// 设置抄送人
String[] ccEmails = email.getCcEmails();
if (ccEmails != null && ccEmails.length != 0) {
InternetAddress[] internetAddressCC = new InternetAddress[ccEmails.length];
for (int i = 0; i < ccEmails.length; i++) {
internetAddressCC[i] = new InternetAddress(ccEmails[i]);
}
message.setRecipients(Message.RecipientType.CC, internetAddressCC);
}
// 设置发生日期
message.setSentDate(new Date());
// 设置邮件主题
message.setSubject(email.getSubject());
/* 创建用于组合邮件正文和附件的MimeMultipart对象 */
// MimeMultipart类表示一个由多个MIME消息组合成的消息
MimeMultipart multipart = new MimeMultipart();
// 设置文本内容
// MimeBodyPart类表示一个MIME消息
MimeBodyPart textContent = new MimeBodyPart();
textContent.setText(email.getContent());
multipart.addBodyPart(textContent);
// 设置附件
String[] attachments = email.getAttachments();
if (attachments != null && attachments.length != 0) {
for (String filename: attachments) {
MimeBodyPart attachPart = createAttachment(filename);
multipart.addBodyPart(attachPart);
}
}
// 将组合的MimeMultipart对象设置为整个邮件的内容,要注意调用saveChanges方法进行更新
message.setContent(multipart);
// 保存并生成最终的邮件内容
message.saveChanges();
return message;
}
/**
* 创建邮件中的附件
* @param filepath 附件的路径
* @return 生成的附件对象
* @throws Exception
*/
public static MimeBodyPart createAttachment(String filepath) throws Exception {
/* 创建一个表示附件的MimeBodyPart对象,并加入附件内容以及相应的信息 */
MimeBodyPart attachPart = new MimeBodyPart();
// FileDataSource用于读取文件数据,并返回代表数据的输入输出流和数据的MIME类型
FileDataSource fileDataSource = new FileDataSource(filepath);
// DataHandler类用于封装FileDataSource对象,并为应用程序提供访问数据的接口
attachPart.setDataHandler(new DataHandler(fileDataSource));
// 设置附件名称,MimeUtility.encodeText可以处理乱码问题
attachPart.setFileName(MimeUtility.encodeText(fileDataSource.getName()));
return attachPart;
}
}
发送结果