一、工具类
package com.thk.utils; import com.thk.domain.MailAccounts; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.*; import java.io.UnsupportedEncodingException; import java.net.URL; import java.util.Date; import java.util.Properties; public class MailSendUtils { /** * 邮箱发送 * * @param mailAccounts * @throws Exception */ public void send(MailAccounts mailAccounts) throws Exception { Message message = getMessage(mailAccounts); // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象 Multipart multipart = new MimeMultipart(); // 创建一个包含HTML内容的MimeBodyPart BodyPart htmlOrTest = new MimeBodyPart(); if (mailAccounts.getIsHtml()) { // 设置HTML内容 htmlOrTest.setContent(mailAccounts.getContent(), "text/html; charset=utf-8"); } else { htmlOrTest.setText(mailAccounts.getContent()); } // 添加发送内容 multipart.addBodyPart(htmlOrTest); if (mailAccounts.getFileUploadNames() != null) { // 添加附件 for (String fileName : mailAccounts.getFileUploadNames()) { addEnclosure(multipart, fileName); } } // 将MiniMultipart对象设置为邮件内容 message.setContent(multipart); Transport.send(message); } /** * 添加附件 * * @param multipart * @param fileName 附件所在的地址 * @throws Exception */ private static void addEnclosure(Multipart multipart, String fileName) throws Exception { BodyPart adjunct = new MimeBodyPart(); FileDataSource fileDataSource = new FileDataSource(fileName); adjunct.setDataHandler(new DataHandler(new URL(fileName))); adjunct.setFileName(changeEncode(fileDataSource.getName())); multipart.addBodyPart(adjunct); } /** * 进行base64加密,防止中文乱码 */ public static String changeEncode(String str) { try { str = MimeUtility.encodeText(new String(str.getBytes(), "UTF-8"), "UTF-8", "B"); // "B"代表Base64 } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return str; } private static Message getMessage(MailAccounts mailAccounts) throws Exception { final Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", mailAccounts.getHost()); properties.setProperty("mail.smtp.auth", mailAccounts.getAuth().toString()); properties.setProperty("mail.smtp.user", mailAccounts.getFrom()); properties.setProperty("mail.smtp.pass", mailAccounts.getPass()); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); //使用JSSE的SSL socketfactory来取代默认的socketfactory properties.put("mail.smtp.socketFactory.fallback", "false"); // 只处理SSL的连接,对于非SSL的连接不做处理 properties.put("mail.smtp.port", mailAccounts.getPort()); properties.put("mail.smtp.socketFactory.port", mailAccounts.getPort()); // 根据邮件会话属性和密码验证器构造一个发送邮件的session Session session = Session.getInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(properties.getProperty("mail.smtp.user"), properties.getProperty("mail.smtp.pass")); } }); session.setDebug(true); Message message = new MimeMessage(session); //消息发送的主题 message.setSubject(mailAccounts.getSubject()); //消息的发送者 message.setFrom(new InternetAddress(properties.getProperty("mail.smtp.user"), mailAccounts.getPersonal())); if (mailAccounts.getTo().length <= 0) { throw new Exception("收件人不能为空!!"); } for (String strAdd : mailAccounts.getTo()) { // 创建邮件的接收者地址,并设置到邮件消息中 message.setRecipient(Message.RecipientType.TO, new InternetAddress(strAdd)); } // 消息发送的时间 message.setSentDate(new Date()); return message; } }
二、实体类
package com.thk.domain;
import lombok.*;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MailAccounts {
/**
* 邮箱地址,就是邮箱服务器的地址,在获取授权码那个页面可以获取到
* <p>
* 这里强烈注意:不用厂家的邮箱地址时不同的。
* </p>
*/
private String host;
/**
* 端口号,SSL模式
*/
private Integer port;
/***
* 设置是否需要用户名密码验证,一般为true
*/
private Boolean auth = true;
/***
* 发送方地址,获取授权码的邮箱
*/
private String from;
/**
* 设置用户名,这个用户名必须是发送方的这个邮箱
*/
private String user;
/***
* 授权码,
*/
private String pass = "授权码" ;
/**
* 发送地址
*/
private String toAddress;
/**
* 发送主题
*/
private String subject;
/**
* 发送内容
*/
private String content;
/**
* 是否为HTML格式,true:是,false:不是
*/
private Boolean isHtml = false;
/**
* 发送者名称
*/
private String personal;
/**
* 对象邮箱
*/
private String[] to;
/**
* 附件路径信息集合
*/
private String[] fileUploadNames = null;
public void setTo(String... to) {
this.to = to;
}
public void setFileUploadNames(String... fileUploadNames) {
this.fileUploadNames = fileUploadNames;
}
}
说明:实体类中的授权码需要到QQ邮箱当中获取
详见:https://jingyan.baidu.com/article/456c463b42f55e4b59314468.html
三、测试
代码:
public static void main(String[] args) { MailSendUtils mailSendUtils = new MailSendUtils(); MailAccounts mailAccounts = new MailAccounts(); mailAccounts.setHost("smtp.qq.com");//邮件地址 mailAccounts.setPort(465);//端口号 mailAccounts.setFrom("");//发送方地址 mailAccounts.setSubject("测试发送邮件");//发送主题 mailAccounts.setContent("测试发送邮件");//发送内容 mailAccounts.setPersonal("测试发送邮件");//发送者名称 mailAccounts.setTo("");//对象邮箱 mailAccounts.setIsHtml(true); try { mailSendUtils.send(mailAccounts); System.out.println("发送成功!"); } catch (Exception e) { e.printStackTrace(); System.out.println("发送失败!"+e.getMessage()); } }
运行结果:
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/119902.html