依赖的jar包
<dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.5.6</version> </dependency>
邮件参数实体
import java.util.List; import java.util.Properties; import com.sun.mail.util.MailSSLSocketFactory; /** * 邮件发送配置参数信息 * @ClassName: MailSenderInfo * @Description: TODO * @author OnlyMate * @Date 2018年5月8日 下午6:27:35 * */ public class MailSenderInfo { // 发送邮件的服务器的IP private String mailServerHost; //发送邮件的服务器端口,该处暂时默认25 private String mailServerPort = "25"; // 邮件发送者的地址 private String fromAddress; // 邮件接收者的地址 private String toAddress; //邮件接收者的地址集合 private String[] toBatchAddress; // 登陆邮件发送服务器的用户名 private String userName; //登陆邮件发送服务器的密码 private String password; // 是否需要身份验证 [默认false不认证] private boolean validate = false; // 邮件主题 private String subject; // 邮件主题 private String[] subjects; // 邮件的文本内容 private String content; // 邮件的文本内容 private String[] contents; // 邮件附件的文件名 private String[] attachFileNames; // 邮件附件的文件名 针对一邮件带多个附件关系 private List<String[]> attachFileList; /** * 获得邮件会话属性 */ public Properties getProperties() { Properties p = new Properties(); try { p.put("mail.smtp.host", this.mailServerHost); p.put("mail.smtp.port", this.mailServerPort); p.put("mail.smtp.auth", validate ? "true" : "false"); p.setProperty("mail.transport.protocol", "smtp"); if("smtp.qq.com".equals(this.mailServerHost)) { MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); p.put("mail.smtp.ssl.enable", "true"); p.put("mail.smtp.ssl.socketFactory", sf); } }catch (Exception e) { e.printStackTrace(); } return p; } /** * 发送邮件的服务器的IP 如:smtp.163.com */ public String getMailServerHost() { return mailServerHost; } /** * 发送邮件的服务器的IP 如:smtp.163.com */ public void setMailServerHost(String mailServerHost) { this.mailServerHost = mailServerHost; } /** * 发送邮件的服务器端口,如:网易邮箱默认25 */ public String getMailServerPort() { return mailServerPort; } /** * 发送邮件的服务器端口,如:网易邮箱默认25 */ public void setMailServerPort(String mailServerPort) { this.mailServerPort = mailServerPort; } /** * 是否需要身份验证 [默认false不认证] */ public boolean isValidate() { return validate; } /** * 是否需要身份验证 [默认false不认证] */ public void setValidate(boolean validate) { this.validate = validate; } /** * 邮件附件的文件名 */ public String[] getAttachFileNames() { return attachFileNames; } /** * 邮件附件的文件名 */ public void setAttachFileNames(String[] fileNames) { this.attachFileNames = fileNames; } /** * 邮件发送者的邮箱地址 */ public String getFromAddress() { return fromAddress; } /** * 邮件发送者的邮箱地址 */ public void setFromAddress(String fromAddress) { this.fromAddress = fromAddress; } /** * 邮件发送者的邮箱密码 */ public String getPassword() { return password; } /** * 邮件发送者的邮箱密码 */ public void setPassword(String password) { this.password = password; } /** * 邮件接收者的地址 */ public String getToAddress() { return toAddress; } /** * 邮件接收者的地址 */ public void setToAddress(String toAddress) { this.toAddress = toAddress; } /** * 邮件接收者的地址集合 * @return */ public String[] getToBatchAddress() { return toBatchAddress; } /** * 邮件接收者的地址集合 * @param toBatchAddress */ public void setToBatchAddress(String[] toBatchAddress) { this.toBatchAddress = toBatchAddress; } /** * 登陆邮件发送服务器的用户名 */ public String getUserName() { return userName; } /** * 登陆邮件发送服务器的用户名 */ public void setUserName(String userName) { this.userName = userName; } /** * 邮件主题 */ public String getSubject() { return subject; } /** * 邮件主题 */ public void setSubject(String subject) { this.subject = subject; } /** * 邮件主题 */ public String[] getSubjects() { return subjects; } /** * 邮件主题 */ public void setSubjects(String[] subjects) { this.subjects = subjects; } /** * 邮件的文本内容 */ public String getContent() { return content; } /** * 邮件的文本内容 */ public void setContent(String textContent) { this.content = textContent; } /** * 邮件的文本内容 */ public String[] getContents() { return contents; } /** * 邮件的文本内容 */ public void setContents(String[] contents) { this.contents = contents; } /** * 针对一邮件多附件 */ public List<String[]> getAttachFileList() { return attachFileList; } /** * 针对一邮件多附件 */ public void setAttachFileList(List<String[]> attachFileList) { this.attachFileList = attachFileList; } }
邮件身份认证
import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; /** * 邮箱参数 * @ClassName: MailAuthenticator * @Description: TODO * @author OnlyMate * @Date 2018年5月8日 下午6:22:59 * */ public class MailAuthenticator extends Authenticator{ String userName=null; String password=null; public MailAuthenticator(){ } public MailAuthenticator(String username, String password) { this.userName = username; this.password = password; } protected PasswordAuthentication getPasswordAuthentication(){ return new PasswordAuthentication(userName, password); } }
邮件发送器
import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Address; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.NoSuchProviderException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; /** * 邮件发送器 * @ClassName: SimpleMailSender * @Description: TODO * @author OnlyMate * @Date 2018年5月8日 下午6:23:20 * */ public class SimpleMailSender { /** * 以文本格式发送邮件 * * @param mailInfo * 待发送的邮件的信息 */ public boolean sendTextMail(MailSenderInfo mailInfo) { // 判断是否需要身份认证 MailAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); if (mailInfo.isValidate()) { // 如果需要身份认证,则创建一个密码验证器 authenticator = new MailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } // 根据邮件会话属性和密码验证器构造一个发送邮件的session Session sendMailSession = Session .getDefaultInstance(pro, authenticator); try { // 根据session创建一个邮件消息 Message mailMessage = new MimeMessage(sendMailSession); // 创建邮件发送者地址 Address from = new InternetAddress(mailInfo.getFromAddress()); // 设置邮件消息的发送者 mailMessage.setFrom(from); // 创建邮件的接收者地址,并设置到邮件消息中 if (mailInfo.getToAddress() != null && mailInfo.getToAddress().length() > 0) { Address to = new InternetAddress(mailInfo.getToAddress()); // Message.RecipientType.TO属性表示接收者的类型为TO mailMessage.setRecipient(Message.RecipientType.TO, to); } else if (mailInfo.getToBatchAddress() != null && mailInfo.getToBatchAddress().length > 0) { final int size = mailInfo.getToBatchAddress().length; Address[] to = new Address[size]; for (int i = 0; i < size; i++) { to[i] = new InternetAddress(mailInfo.getToBatchAddress()[i]); } // Message.RecipientType.TO属性表示接收者的类型为TO mailMessage.setRecipients(Message.RecipientType.TO, to); } // 设置邮件消息的主题 mailMessage.setSubject(mailInfo.getSubject()); // 设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); // 设置邮件消息的主要内容 String mailContent = mailInfo.getContent(); mailMessage.setText(mailContent); // 发送邮件 Transport.send(mailMessage); return true; } catch (MessagingException ex) { ex.printStackTrace(); } return false; } /** * 以HTML格式发送邮件 * * @param mailInfo * 待发送的邮件信息 */ public boolean sendHtmlMail(MailSenderInfo mailInfo) { // 判断是否需要身份认证 MailAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); // 如果需要身份认证,则创建一个密码验证器 if (mailInfo.isValidate()) { authenticator = new MailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } // 根据邮件会话属性和密码验证器构造一个发送邮件的session Session sendMailSession = Session .getDefaultInstance(pro, authenticator); try { sendMailSession.setDebug(true); // 根据session创建一个邮件消息 Message mailMessage = new MimeMessage(sendMailSession); // 创建邮件发送者地址 Address from = new InternetAddress(mailInfo.getFromAddress()); // 设置邮件消息的发送者 mailMessage.setFrom(from); // 创建邮件的接收者地址,并设置到邮件消息中 if (mailInfo.getToAddress() != null && mailInfo.getToAddress().length() > 0) { Address to = new InternetAddress(mailInfo.getToAddress()); // Message.RecipientType.TO属性表示接收者的类型为TO mailMessage.setRecipient(Message.RecipientType.TO, to); } else if (mailInfo.getToBatchAddress() != null && mailInfo.getToBatchAddress().length > 0) { final int size = mailInfo.getToBatchAddress().length; Address[] to = new Address[size]; for (int i = 0; i < size; i++) { to[i] = new InternetAddress(mailInfo.getToBatchAddress()[i]); } // Message.RecipientType.TO属性表示接收者的类型为TO mailMessage.setRecipients(Message.RecipientType.TO, to); } // 设置邮件消息的主题 mailMessage.setSubject(mailInfo.getSubject()); mailMessage.setSubject(MimeUtility.encodeText(mailInfo.getSubject(), "UTF-8", "B")); // 设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象 Multipart mainPart = new MimeMultipart(); //-------------------------------beigin 文本---------------------// // 创建一个包含HTML内容的MimeBodyPart BodyPart html = new MimeBodyPart(); // 设置HTML内容 html.setContent(mailInfo.getContent(), "text/html; charset=utf-8"); mainPart.addBodyPart(html); //----------------------------------end 文本---------------------// //-------------------------------beigin 附件---------------------// if(mailInfo.getAttachFileList() != null && mailInfo.getAttachFileList().size() > 0){ for (String[] files : mailInfo.getAttachFileList()) { for (String file : files) { //邮件的附件 String fileName = file; if(fileName != null&&!fileName.trim().equals("")) { MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fileSource = new FileDataSource(fileName); mbp.setDataHandler(new DataHandler(fileSource)); try { mbp.setFileName(MimeUtility.encodeText(fileSource.getName())); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } mainPart.addBodyPart(mbp); } } } } else { if(mailInfo.getAttachFileNames() != null && mailInfo.getAttachFileNames().length > 0){ //邮件的附件 String fileName = mailInfo.getAttachFileNames()[0]; if(fileName != null&&!fileName.trim().equals("")) { MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fileSource = new FileDataSource(fileName); mbp.setDataHandler(new DataHandler(fileSource)); try { mbp.setFileName(MimeUtility.encodeText(fileSource.getName())); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } mainPart.addBodyPart(mbp); } } } //----------------------------------end 附件---------------------// // 将MiniMultipart对象设置为邮件内容 mailMessage.setContent(mainPart); // 发送邮件 Transport.send(mailMessage); System.out.println("发送成功!"); return true; } catch (MessagingException ex) { ex.printStackTrace(); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return false; } /** * 以HTML格式发送多封邮件 * * @param mailInfo * 待发送的邮件信息 */ public boolean sendBatchHtmlMail(MailSenderInfo mailInfo) { // 判断是否需要身份认证 MailAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); pro.setProperty("mail.transport.protocol", "smtp"); // 如果需要身份认证,则创建一个密码验证器 if (mailInfo.isValidate()) { authenticator = new MailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } // 根据邮件会话属性和密码验证器构造一个发送邮件的session Session sendMailSession = Session.getInstance(pro, authenticator); try { // 发送邮件 sendMailSession.setDebug(true); Transport transport = sendMailSession.getTransport(); transport.connect(mailInfo.getMailServerHost(),Integer.parseInt(mailInfo.getMailServerPort()), mailInfo.getUserName(), mailInfo.getPassword()); // 创建邮件的接收者地址,并设置到邮件消息中 if (mailInfo.getToBatchAddress() != null && mailInfo.getToBatchAddress().length > 0) { final int size = mailInfo.getToBatchAddress().length; for (int i = 0; i < size; i++) { // 根据session创建一个邮件消息 Message mailMessage = new MimeMessage(sendMailSession); // 创建邮件发送者地址 Address from = new InternetAddress(mailInfo.getFromAddress()); // 设置邮件消息的发送者 mailMessage.setFrom(from); // 设置邮件消息的主题 mailMessage.setSubject(mailInfo.getSubjects()[i]); mailMessage.setSubject(MimeUtility.encodeText(mailInfo.getSubjects()[i], "UTF-8", "B")); // 设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象 Multipart mainPart = new MimeMultipart(); //-------------------------------beigin 文本---------------------// // 创建一个包含HTML内容的MimeBodyPart BodyPart html = new MimeBodyPart(); // 设置HTML内容 html.setContent(mailInfo.getContents()[i], "text/html; charset=utf-8"); mainPart.addBodyPart(html); //----------------------------------end 文本---------------------// //-------------------------------beigin 附件---------------------// if(mailInfo.getAttachFileList() != null && mailInfo.getAttachFileList().size() > 0){ String[] files = mailInfo.getAttachFileList().get(i); for (String file : files) { //邮件的附件 String fileName = file; if(fileName != null&&!fileName.trim().equals("")) { MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fileSource = new FileDataSource(fileName); mbp.setDataHandler(new DataHandler(fileSource)); try { mbp.setFileName(MimeUtility.encodeText(fileSource.getName())); //System.out.println("ceshi2: " + MimeUtility.encodeText(fileSource.getName(),"utf-8",null)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } mainPart.addBodyPart(mbp); } } } else { if(mailInfo.getAttachFileNames() != null && mailInfo.getAttachFileNames().length > 0){ //邮件的附件 String fileName = mailInfo.getAttachFileNames()[i]; if(fileName != null&&!fileName.trim().equals("")) { MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fileSource = new FileDataSource(fileName); mbp.setDataHandler(new DataHandler(fileSource)); try { mbp.setFileName(MimeUtility.encodeText(fileSource.getName())); //System.out.println("ceshi: " + MimeUtility.encodeText(fileSource.getName(),"utf-8",null)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } mainPart.addBodyPart(mbp); } } } //----------------------------------end 附件---------------------// // 将MiniMultipart对象设置为邮件内容 mailMessage.setContent(mainPart); Address[] to = new Address[]{new InternetAddress(mailInfo.getToBatchAddress()[i])}; mailMessage.setRecipient(Message.RecipientType.TO, to[0]); transport.sendMessage(mailMessage, to); } } transport.close(); System.out.println("发送成功!"); return true; } catch (AddressException e) { e.printStackTrace(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return false; } }
测试
import java.util.Date; import java.util.Properties; import javax.mail.Address; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import com.only.mate.email.MailAuthenticator; import com.only.mate.email.MailSenderInfo; import com.only.mate.email.SimpleMailSender; import com.sun.mail.util.MailSSLSocketFactory; public class EmailTest { private MailSenderInfo mailSenderInfo; public static void main(String[] args) throws Exception { EmailTest test = new EmailTest(); // test.sendTextEmail1(); // test.sendTextEmail(); test.sendHtmlEmail(); } { mailSenderInfo = new MailSenderInfo(); mailSenderInfo.setMailServerHost("smtp.qq.com"); mailSenderInfo.setMailServerPort("465"); mailSenderInfo.setUserName("*********@qq.com"); mailSenderInfo.setPassword("***********"); mailSenderInfo.setFromAddress("********@qq.com"); mailSenderInfo.setToAddress("********@qq.com"); mailSenderInfo.setValidate(true); mailSenderInfo.setSubject("主题-你猜猜?"); Date date = new Date(); String content = String.format( "<!DOCTYPE html>"+ "<html lang=\"en\">"+ "<head>"+ "<meta charset=\"UTF-8\" />"+ "<title></title>"+ "</head>"+ "<style type=\"text/css\">heml,body{margin: 0;padding: 0;font-size: 14px;}.container{width: 880px;margin:0 auto;background: #e7f5ff;height:800px;padding-top: 80px;margin-top: 20px;}.container-con{width:680px;margin:0 auto;background:#fff;height:600px;padding:20px;}.eamil-top{font-size: 14px;}.eamil-top>span{color:#000;font-weight: bold;}.eamil-top2{font-size: 14px;padding-left: 16px;margin-bottom: 30px;}.eamil-con{padding:20px;}.eamil-con>p{line-height: 20px;}.top-img{background:url(\"images/tt0_03.png\") no-repeat;background-size: cover; width:722px;height:100px;margin:0 auto;}.fpptwe{line-height: 30px;}.footer{float: right;}.jingao{font-size: 12px;color:#888}</style>"+ "<body>"+ "<div class=\"container\">"+ "<div class=\"top-img\"></div>"+ "<div class=\"container-con\">"+ "<p class=\"eamil-top\">"+ "尊敬的XX女士"+ "</p>"+ "<p class=\"eamil-top2\">您好!</p>"+ "<div class=\"eamil-con\">"+ "<p>您所提交“XXX”的申请,已通过。</p>"+ "<p>"+ "请及时前往去享受!<span>%s</span>"+ "</p>"+ "<img src='http://img.mp.itc.cn/upload/20160326/73a64c935e7d4c9594bdf86d76399226_th.jpg' />"+ "</div>"+ "<p class=\"jingao\">(这是一封系统自动发送的邮件,请不要直接回复。)</p>"+ "<div class=\"footer\">"+ "<p>爱的港湾</p>"+ "<span>%tF %tT</span>"+ "</div>"+ "</p>"+ "</div>"+ "</div>"+ "</body>"+ "</html>", "❤☻☻☻☻❤", date, date); mailSenderInfo.setContent(content); // mailSenderInfo.setContent("其实只是好玩而已"); mailSenderInfo.setAttachFileNames(new String[] {"C:/Users/OnlyMate/Pictures/MyPhoneTheme.jpg"}); } public void sendTextEmail() throws Exception { SimpleMailSender sender = new SimpleMailSender(); sender.sendTextMail(mailSenderInfo); } public void sendHtmlEmail() throws Exception { SimpleMailSender sender = new SimpleMailSender(); sender.sendHtmlMail(mailSenderInfo); } public void sendTextEmail1() throws Exception { Properties props = new Properties(); // 开启debug调试 props.setProperty("mail.debug", "false"); // 发送服务器需要身份验证 props.setProperty("mail.smtp.auth", "true"); // 使用 STARTTLS安全连接 props.put("mail.smtp.starttls.enable", "true"); // 设置邮件服务器主机名 props.setProperty("mail.smtp.host", mailSenderInfo.getMailServerHost()); // 设置邮件服务器端口 props.put("mail.smtp.port", mailSenderInfo.getMailServerPort()); // 发送邮件协议名称 props.setProperty("mail.transport.protocol", "smtp"); MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); props.put("mail.smtp.ssl.enable", "true"); props.put("mail.smtp.ssl.socketFactory", sf); // 如果需要身份认证,则创建一个密码验证器 MailAuthenticator authenticator = new MailAuthenticator(mailSenderInfo.getUserName(), mailSenderInfo.getPassword()); // 根据邮件会话属性和密码验证器构造一个发送邮件的session Session session = Session.getDefaultInstance(props, authenticator); Message msg = new MimeMessage(session); msg.setSubject("主题-你猜猜?"); StringBuilder builder = new StringBuilder(); builder.append("测试邮件: 我用Java代码给你发送了一份邮件!我的❤你收到了吗?"); msg.setText(builder.toString()); msg.setFrom(new InternetAddress(mailSenderInfo.getUserName())); Address to = new InternetAddress(mailSenderInfo.getToAddress()); // Message.RecipientType.TO属性表示接收者的类型为TO msg.setRecipient(Message.RecipientType.TO, to); Transport.send(msg); /*Transport transport = session.getTransport("smtp"); transport.connect(mailSenderInfo.getMailServerHost(),mailSenderInfo.getUserName(), "irfydcgrkxembbii"); transport.sendMessage(msg, new Address[] { new InternetAddress("*****@qq.com") }); transport.close();*/ } }
说明:QQ普通用户只用使用:
mail.smtp.host = "smtp.qq.com";
mail.smtp.port = "465";
要开启SSL
QQ企业用户只能使用:
mail.smtp.host = "smtp.exmail.qq.com";
mail.smtp.port = "25";
不开启SSL