maven依赖
<!-- 邮箱 -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.5.0-b01</version>
</dependency>
qq邮箱工具类:
tip: 邮箱授权码,需要在qq邮箱里找到设置->常规->smtp服务,把POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务打开,获取到授权码。
package org.wq.email;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Email {
public static final String SenderEmail = "123456@qq.com";//发送人邮箱
public static final String senderCode = "";//发送人邮箱授权码
public static final String emailSMTPHost = "smtp.qq.com";//服务器地址
//public static final String receiveMailAccount = "123456@qq.com";//收件人邮箱
/*发送邮件*/
public static void sendMail(String path) {
//收件人邮箱
List<String> emailList = new ArrayList<>();
emailList.add("123456@qq.com");
//emailList.add("wangjj@numtop.com");
for (String to : emailList) {
try {
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");// 使用的协议
props.setProperty("mail.smtp.host", emailSMTPHost);// 发件人的邮箱的SMTP服务器地址
props.setProperty("mail.smtp.auth", "true");// 需要请求认证
Session session = Session.getInstance(props);//得到会话对象实例
session.setDebug(false);//是否打印详细日志
MimeMessage message = createMimeMessage(session,path,to);//获取邮件对象
Transport transport = session.getTransport();
transport.connect(SenderEmail, senderCode);//连接发送人的邮箱账户
// 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
transport.sendMessage(message, message.getAllRecipients());
// 7. 关闭连接
transport.close();
System.out.println("邮件发送成功!to=>" + to);
} catch (Exception e) {
System.out.println("邮件发送失败:"+ e);
}
}
}
public static MimeMessage createMimeMessage(Session session, String str, String to) throws Exception {
//解析字符串,取出文件路径,文件名,content
String[] split = str.split("@");
String path = split[0];
String fileName = split[1];
String content = split[2];
System.out.println("文件路径:"+path);
System.out.println("文件名:"+fileName);
System.out.println("content:"+content);
// 1. 创建一封邮件
MimeMessage message = new MimeMessage(session);
// 2. From: 发件人
message.setFrom(new InternetAddress(SenderEmail, "发件人", "UTF-8"));
// 3. 设置收件人、抄送人、密送人
//MimeMessage.RecipientType.TO:收件类型;MimeMessage.RecipientType.CC:抄送类型;MimeMessage.RecipientType.BCC:密送类型
message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to, "收件人", "UTF-8"));
// message.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress(ccMailAccount, "抄送人", "UTF-8"));
// message.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress(bccmailAccount, "密送人", "UTF-8"));
// 4. Subject: 邮件主题
message.setSubject("subject", "UTF-8");
// 5. Content: 邮件正文(可以使用html标签)
// 创建消息部分
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(content);
// 创建多部分消息
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// 添加附件
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.attachFile(path); // 附件文件路径
attachmentPart.setFileName(MimeUtility.encodeText(fileName+".xlsx")); // 对文件名进行编码
multipart.addBodyPart(attachmentPart);
// 设置消息内容
message.setContent(multipart);
// 6. 设置发件时间
message.setSentDate(new Date());
// 7. 保存设置
message.saveChanges();
return message;
}
}
exchange邮箱工具类:
package org.wq.email;
import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
public class EmailByExChange {
private static String from = "发送人邮箱";
/**
* 发送邮件
* @param str
*/
public static void sendMail(String str) throws GeneralSecurityException, MessagingException {
//解析字符串,取出文件路径,文件名,content
String[] split = str.split("@");
String path = split[0];
String fileName = split[1];
String content = split[2];
System.out.println("文件路径:"+path);
System.out.println("文件名:"+fileName);
System.out.println("content:"+content);
//收件人邮箱
List<String> emailList = new ArrayList<>();
emailList.add("123456@qq.com");
for (String to : emailList) {
final String username = "admin";
final String password = "admin";
Properties props = new Properties();
props.put("mail.smtp.host", "");//smtp地址
props.put("mail.smtp.port", "");//端口
props.put("mail.smtp.auth", "true");
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(from));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
//主题
message.setSubject("subject");
// Create a multipart message
Multipart multipart = new MimeMultipart();
// 普通正文
BodyPart messageBodyPart = new MimeBodyPart();
List<String> list = Arrays.asList(content.split(","));
String contentStr = "";
for (String string : list) {
contentStr = contentStr + string + "\n";
}
System.out.println(contentStr);
messageBodyPart.setText(contentStr);
multipart.addBodyPart(messageBodyPart);
//html正文(中文乱码)
// List<String> list = Arrays.asList(content.split(","));
// String contentStr = "";
// for (String string : list) {
// contentStr = contentStr + string + "</br>";
// }
// System.out.println("html:"+contentStr);
//
// BodyPart messageBodyPart = new MimeBodyPart();
// String htmlContent = "<html><head><meta charset='UTF-8'/></head><body><p>"+
// contentStr
// +"</p></body></html>";
// System.out.println(htmlContent);
//
// messageBodyPart.setContent(htmlContent, "text/html");
// multipart.addBodyPart(messageBodyPart);
// 附件
BodyPart attachmentPart = new MimeBodyPart();
DataSource source = new FileDataSource(path);
attachmentPart.setDataHandler(new DataHandler(source));
// 文件名编码
String encodedFileName = MimeUtility.encodeText(fileName + ".xlsx");
attachmentPart.setFileName(encodedFileName);
multipart.addBodyPart(attachmentPart);
// Set the message content
message.setContent(multipart);
// Send the message
Transport.send(message);
System.out.println("邮件发送成功!to=>"+to);
} catch (MessagingException e) {
throw new RuntimeException(e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
}