package com.fdkankan.ucenter.util; import com.sun.mail.util.MailSSLSocketFactory; import org.apache.commons.lang3.StringUtils; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.*; import java.io.File; import java.util.Properties; /** * Created by Hb_zzZ on 2020/3/16. */ public class SendMailUtils { /** * 发送带附件的邮件 * @param from 发件人 * @param pass 发件人密码 * @param host 发件人主机 * @param receive 收件人 * @param subject 邮件主题 * @param msg 邮件内容 * @param filename 附件地址 * */ public static boolean sendMail(String from,String pass,String host, String receive, String subject, String msg, String filename) { if (StringUtils.isEmpty(receive)) { return false; } try { // 获取系统属性 Properties properties = System.getProperties(); // 设置邮件服务器 properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.debug", "true"); properties.put("mail.smtp.auth", "true"); MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); properties.put("mail.smtp.ssl.enable", "true"); properties.put("mail.smtp.ssl.socketFactory", sf); // 获取默认session对象 Session session = Session.getDefaultInstance(properties, new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { // qq邮箱服务器账户、第三方登录授权码 return new PasswordAuthentication(from, pass); // 发件人邮件用户名、密码 } }); // 创建默认的 MimeMessage 对象 MimeMessage message = new MimeMessage(session); // Set From: 头部头字段 message.setFrom(new InternetAddress(from)); // Set To: 头部头字段 message.addRecipient(Message.RecipientType.TO, new InternetAddress(receive)); // Set Subject: 主题文字 message.setSubject(subject); MimeMultipart multipart = new MimeMultipart("mixed"); MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(msg, "text/html;charset=utf-8"); multipart.addBodyPart(htmlPart); if (StringUtils.isNotBlank(filename)) { File file = new File(filename); if (file.exists()) { MimeBodyPart attachmentPart = new MimeBodyPart(); DataSource source = new FileDataSource(file); attachmentPart.setDataHandler(new DataHandler(source)); attachmentPart.setFileName( MimeUtility.encodeText(file.getName(), "UTF-8", "B") ); multipart.addBodyPart(attachmentPart); } } message.setContent(multipart); Transport.send(message); return true; } catch (Exception e) { e.printStackTrace(); } return false; } }