一、java mail发送邮件:
1.pom.xml
<dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.2</version> </dependency>
2.代码
2.1email实体类
@Data public class EmailDto { private String serverName; private String port; private String userName; private String password; private String senderName; private String emailAddress; private String subject; private String to; private String cC; private String content; @Override public String toString() { return JSONObject.toJSONString(this); } }
public class MailUtils { /** * 发送邮件 * @param emailDto email配置信息 * @param filePath 本地附件地址 */ public static void sendMail(EmailDto emailDto, JSONArray filePath) { Transport transport = null; try { Properties prop = new Properties(); prop.setProperty("mail.host", emailDto.getServerName()); //邮箱发送 prop.setProperty("mail.transport.protocol", "smtp"); // 邮件发送协议 prop.setProperty("mail.smtp.auth", "true"); // 需要验证用户名密码 //1、创建定义整个应用程序所需的环境信息的 Session 对象 Session session = Session.getDefaultInstance(prop, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { //传入发件人的姓名和授权码 return new PasswordAuthentication(emailDto.getUserName(), emailDto.getPassword()); } }); //2、通过session获取transport对象 transport = session.getTransport(); //3、通过transport对象邮箱用户名和授权码连接邮箱服务器 transport.connect(emailDto.getServerName(), emailDto.getUserName(), emailDto.getPassword()); //4、创建邮件,传入session对象 MimeMessage mimeMessage = getMimeMessage(session, emailDto, filePath); //5、发送邮件 transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); } catch (Exception e) { e.printStackTrace(); } finally { if (transport != null) { try { transport.close(); } catch (MessagingException e) { e.printStackTrace(); } } } } /** * 组装发送信息 * @param session session * @param emailDto 邮件配置信息 * @param filesPath 本地地址 * @return MimeMessage * @throws Exception Exception */ private static MimeMessage getMimeMessage(Session session, EmailDto emailDto, JSONArray filesPath) throws Exception { //消息的固定信息 MimeMessage mimeMessage = new MimeMessage(session); //发件人 mimeMessage.setFrom(new InternetAddress(emailDto.getEmailAddress())); //收件人 if (StringUtils.isNotBlank(emailDto.getTo())) { String[] tos = emailDto.getTo().split(","); for (String to : tos) { mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } //抄送人 if (StringUtils.isNotBlank(emailDto.getCC())) { String[] ccs = emailDto.getTo().split(","); for (String cc : ccs) { mimeMessage.setRecipient(Message.RecipientType.CC, new InternetAddress(cc)); } } //邮件标题 mimeMessage.setSubject(emailDto.getSubject()); MimeMultipart multipart = new MimeMultipart(); //附件 for (Object pathObj : filesPath) { MimeBodyPart attachPart = new MimeBodyPart(); File file = new File((String) pathObj); attachPart.setDataHandler(new DataHandler(new FileDataSource(file))); //避免中文乱码的处理 attachPart.setFileName(MimeUtility.encodeWord(file.getName())); multipart.addBodyPart(attachPart);//附件 } //正文 MimeBodyPart contentPart = new MimeBodyPart(); contentPart.setContent(emailDto.getContent(), "text/html;charset=utf-8"); multipart.addBodyPart(contentPart); multipart.setSubType("mixed"); //正文和附件都存在邮件中,所有类型设置为mixed //放到Message消息中 mimeMessage.setContent(multipart); mimeMessage.saveChanges();//保存修改 return mimeMessage; } }
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
/** * 创建邮件发送器 * * @param emailDto 邮件配置信息 * @return 发送器 */ private static JavaMailSenderImpl createMailSender(EmailDto emailDto) { JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setHost(emailDto.getServerName()); sender.setPort(Integer.parseInt(emailDto.getPort())); sender.setUsername(emailDto.getUserName()); sender.setPassword(emailDto.getPassword()); sender.setDefaultEncoding("Utf-8"); Properties p = new Properties(); p.setProperty("mail.smtp.timeout", "25000"); p.setProperty("mail.smtp.auth", "false"); sender.setJavaMailProperties(p); return sender; } /** * 发送邮件 * * @param emailDto emailDto * @param files files(由于附件是服务接收的,故我这里用MultipartFile) * @throws MessagingException * @throws UnsupportedEncodingException 自定义异常,可忽略 */ public void sendMail(EmailDto emailDto, MultipartFile... files) throws MessagingException, UnsupportedEncodingException { long startTime = System.currentTimeMillis(); JavaMailSenderImpl mailSender = createMailSender(emailDto); MimeMessage mimeMessage = mailSender.createMimeMessage(); // 设置utf-8或GBK编码,否则邮件会有乱码 MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8"); messageHelper.setFrom(emailDto.getEmailAddress(), emailDto.getSenderName()); messageHelper.setTo(emailDto.getTo().split(",")); messageHelper.setSubject(emailDto.getSubject()); messageHelper.setText(emailDto.getContent(), true); if (StringUtils.isNotBlank(emailDto.getCC())) { messageHelper.setCc(emailDto.getCC().split(",")); } for (MultipartFile file : files) { if (!file.isEmpty() && file.getOriginalFilename() != null) { messageHelper.addAttachment(file.getOriginalFilename(), file); } } mailSender.send(mimeMessage); log.info("邮件发送耗时:" + (System.currentTimeMillis() - startTime) / 1000.0); }
三、使用Apache commons-email发送html邮件
1.pom.xml
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-email</artifactId> <version>1.5</version> </dependency>
import org.apache.commons.mail.EmailException; import org.apache.commons.mail.HtmlEmail; import java.util.List; /** * @className: MailUtil.java * @description: 邮件工具类 */ public class MailUtil { /** * 构建器 */ public static class EmailInfo { /** * SMTP 服务器 端口 */ private String mailServer; private Integer mailPort; /** * 发件人 账号 */ private String mailNick; /** * 发件人 账号 */ private String mailUsername; /** * 发件人 密码 */ private String mailPassword; /** * 邮件标题 */ private String title; /** * 邮件内容 */ private String content; /** * 收件人 */ private List<String> receivers; boolean ssl; public EmailInfo(String mailServer,Integer mailPort,String mailNick,String mailUsername, String mailPassword,String title,String content,List<String> receivers,boolean ssl) { this.mailServer = mailServer; this.mailPort = mailPort; this.mailNick = mailNick; this.mailUsername = mailUsername; this.mailPassword = mailPassword; this.title = title; this.content = content; this.receivers = receivers; this.ssl = ssl; } public MailUtil send() throws Exception { return new MailUtil(this); } } private MailUtil(EmailInfo emailInfo) throws Exception { HtmlEmail email = new HtmlEmail(); // 通过Server 发送邮件 email.setHostName(emailInfo.mailServer); email.setSmtpPort(emailInfo.mailPort); //设定smtp服务器的认证资料信息 email.setAuthentication(emailInfo.mailUsername, emailInfo.mailPassword); email.setStartTLSEnabled(false); email.setSSLOnConnect(emailInfo.ssl); try { // 设定发件人 email.setFrom(emailInfo.mailUsername,emailInfo.mailNick); // 设定收件人 (多人) int size = emailInfo.receivers.size(); email.addTo(emailInfo.receivers.toArray(new String[size])); // 设定内容的语言集 email.setCharset("UTF-8"); email.setDebug(false); // 设定主题 email.setSubject(emailInfo.title); // 设定邮件内容 email.setHtmlMsg(emailInfo.content); // 发送邮件 email.send(); System.out.println("邮件发送成功!"); } catch (EmailException e) { System.out.println("邮件发送失败!"); throw new Exception(e); } } }