java 发送邮件email

322 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

发送邮件

一、添加maven依赖:

<groupId>com.sun.mail</groupId>

<artifactId>javax.mail</artifactId>

<version>1.6.0</version>

二、email工具类

import com.jfinal.log.Log;
import com.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.util.Date;
import java.util.Properties;
 
public class EmailUtil {
 
    private static final  Log log = Log.getLog(EmailUtil.class);
    protected Session session;
 
    /**
     * 获取系统环境
     */
    public static Properties getEmailProperties() {
        Properties prop = new Properties();
        return prop;
    }
 
    /**
     * 初始化 SMTP 服务
     * @param prop
     * @param host 发件人的邮箱的 SMTP 服务器地址
     * @param port 端口
     * @param ssl  是否使用SSL
     * @return
     */
    public static Properties initSMTP(Properties prop, String host, int port, boolean ssl) {
        prop.setProperty("mail.smtp.host", host);
        prop.setProperty("mail.smtp.auth", "true");
        prop.setProperty("mail.smtp.port", String.valueOf(port));
        prop.setProperty("mail.smtp.ssl.enable", ssl ? "true" : "false");
        if (ssl) {
            prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            prop.setProperty("mail.smtp.socketFactory.fallback", "false");
        }
        return prop;
    }
 
    /**
     * 企业邮箱服务器
     * @param prop
     * @return
     */
    public static Properties setSMTP_qq(Properties prop) {
        return initSMTP(prop, "smtp.exmail.qq.com", 465, true);
    }
 
    /**
     *
     * @param prop
     * @param host
     * @return prop
     * @throws MessagingException
     */
    public static Properties setSMTP_sel(Properties prop, String host) throws MessagingException {
       if (host.contains("126.com") || host.equals("163.com")) { // 网易
            return initSMTP(prop, "smtp.126.com", 25, true);
        } else if (host.contains("sina.com")) { // 新浪
            return initSMTP(prop, "smtp.sina.com", 25, true);
        } else if (host.contains("qq.com")) { // 新浪
            return initSMTP(prop, "smtp.qq.com", 465, true);
        } else {
            throw new MessagingException("not support for host[" + host + "]");
        }
    }
 
    /**
     * 初始化session
     * @param prop
     * @return
     */
    public Session initSession(Properties prop){
        Session session = Session.getInstance(prop);
        // 在控制台显示Debug信息
        session.setDebug(true);
        this.session = session;
        return session;
    }
 
    /**
     * 创建一封邮箱
     * @param session
     * @param subject
     * @param content
     * @param sendMail
     * @param sendPersonName
     * @param receiveMail
     * @param receivePersonName
     * @return message
     * @throws Exception
     */
    public static MimeMessage createMimeMessage(Session session, String subject, String content, String sendMail, String sendPersonName, String receiveMail, String receivePersonName) throws Exception {
        MimeMessage message = new MimeMessage(session);
        // From: 发件人
        message.setFrom(new InternetAddress(sendMail, sendPersonName, "UTF-8"));
        // To: 收件人
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, receivePersonName, "UTF-8"));
        // Subject: 邮件主题
        message.setSubject(subject, "UTF-8");
        // Content: 邮件正文
        message.setContent(content, "text/html;charset=UTF-8");
        // 设置发件时间
        message.setSentDate(new Date());
        // 保存设置
        message.saveChanges();
        return message;
    }
 
    /**
     * 创建一封邮箱带多附件
     * @param session
     * @param subject
     * @param content
     * @param sendMail
     * @param sendPersonName
     * @param receiveMail
     * @param receivePersonName
     * @return message
     * @throws Exception
     */
    public static MimeMessage createMimeMessage2(Session session, String subject, String content, String sendMail, String sendPersonName, String receiveMail, String receivePersonName, File ...file) throws Exception {
        MimeMessage message = new MimeMessage(session);
        // From: 发件人
        message.setFrom(new InternetAddress(sendMail, sendPersonName, "UTF-8"));
        // To: 收件人
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, receivePersonName, "UTF-8"));
        // Subject: 邮件主题
        message.setSubject(subject, "UTF-8");
        //添加附件+正文
        MimeBodyPart body0 = new MimeBodyPart();
        body0.setContent(content, "text/html;charset=UTF-8");
        MimeMultipart mmPart = new MimeMultipart();
        mmPart.addBodyPart(body0);
        for (int i = 0; i < file.length; i++){
            MimeBodyPart body = new MimeBodyPart();
            body.setDataHandler(new DataHandler(new FileDataSource(file[i])));
            body.setFileName(MimeUtility.encodeText(file[i].getName()));
            mmPart.addBodyPart(body);
        }
        message.setContent(mmPart);
        // 设置发件时间
        message.setSentDate(new Date());
        // 保存设置
        message.saveChanges();
        return message;
    }
 
 
    /**
     * 发送邮件
     * @param message
     * @param sendAccount
     * @param sendPassword
     * @return
     */
    public boolean send(MimeMessage message, String sendAccount, String sendPassword) {
        try{
            Transport transport = session.getTransport();
            transport.connect(sendAccount, sendPassword);
            log.info("开始发送邮件····");
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            log.info("邮件发送成功!");
            return true;
        } catch (NoSuchProviderException e) {
            log.error("邮件发送失败!"+ e);
            e.printStackTrace();
        } catch (javax.mail.MessagingException e) {
            log.error("邮件发送失败!"+ e);
            e.printStackTrace();
        }
        return false;
    }
 
         public static void main(String[] args) throws Exception {
          
 
 /**
 * qq邮箱发送模板
 */
EmailUtil emailUtil=new EmailUtil();
Properties properties = EmailUtil.getEmailProperties();
properties = EmailUtil.setSMTP_sel(properties, "qq.com");
MimeMessage message = EmailUtil.createMimeMessage(emailUtil.initSession(properties), "这是主题", "这是内容", "***@qq.com(发件人)", "发件人姓名","***********@qq.com", "收件人姓名");
boolean flag = emailUtil.send(message, "***@qq.com(发件人)", "这里输入密码(发件人密码),qq邮箱则是授权码");
if (flag){
    log.info("邮件发送成功!");
}else{
    log.error("邮件发送失败!");
}}

注意:

  1. 若是发送qq邮箱:输入的密码不是qq密码,是授权码。如何获取授权码:需要进入qq邮箱,开启pop3/smtp服务。 (登录qq邮箱-->设置-->账户:里面有开启pop3/smtp服务,点击开启后即可获取授权码)

2.如果邮件发送错误,一定要看它所返回的错误消息,很有用。如果返回url链接,记得点进去看,是什么错误

模板引擎:

一、 添加依赖

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

二、 添加模板

在resource目录下添加--->templates---->mail.html

mail.html内容如下:

<html>
<body>
    <div>
        <p>这是邮件模板: ${userName}</p>
    </div>
</body>
</html>

三、获取邮件模板

/**
     * 绑定邮件模板
     * @param userName
     * @return
     * @throws IOException
     * @throws TemplateException
     */
    private String getEmailTemplate(String userName) throws IOException, TemplateException {
        Template template = null;
        Map<String, Object> model = new HashMap<>();
        model.put("userName", userName);
        template = freeMarkerConfigurer.getConfiguration().getTemplate("mail.html");
        String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
        return html;
    }

四、 发送邮件模板

将该处获取到的邮件模板html,作为邮件内容content发送即可