[Java工具] 邮件发送工具

更新

  • 2018 10-16更新:添加功能,使用配置文件方式配置邮箱信息,并可以动态加载配置文件

注册邮箱

去163邮箱(或其他邮箱)注册一个邮箱,并开启SMTP授权码。

程序

需要注意的是,由于阿里云服务器不让使用默认的25端口,所以会出现Windows下测试发送邮件成功,Linux服务器下发送邮件却出错的问题(broke pipe、timeout、can not connect等)。解决办法是使用带SSL的465端口。

package com.kuyuntech.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.Security;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * 邮件发送工具类
 * 功能:1. 发送邮件
 *      2. 动态配置邮箱信息
 *         用户可以修改配置文件,等待一定时间后会自动更新,不需要重启应用
 *
 * 注意:1. 暂时只能使用163邮箱,其他邮箱未测试
 *      2. 需要搭配配置文件使用,配置文件路径在 CONFIG_FILE_LOCATION 中配置(全路径)
 *      3. 可以配置配置文件更新时间间隔,在 UPDATE_MINUTES 中配置
 *
 * @author zp
 */
public class EmailUtils {

    // 配置文件路径(路径+文件名) 注意是绝对路径
    private static final String CONFIG_FILE_LOCATION = "/Users/spz/work/project/kuyun_brn/src/main/resources/email.properties";
    // 配置文件的更新时间(单位:分)
    private static final long UPDATE_MINUTES = 1;

    /**
     * 发送邮件
     * @param toUser    :收件人
     * @param title     :标题
     * @param content   :内容
     */
    public static void sendMail(String toUser,String title,String content) throws Exception {

        EmailConfig.emailConfig.updateConfigFile();//定时更新配置文件

        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        Properties props = System.getProperties();
        props.setProperty("mail.smtp.host", EmailConfig.emailConfig.mailSmtpHost);
        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", "465");// 不能使用25端口,因为阿里云服务器禁止使用25端口,所以必须使用ssl的465端口
        props.setProperty("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(props, new Authenticator(){
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(EmailConfig.emailConfig.userName, //邮箱账号
                        EmailConfig.emailConfig.password); //授权码
            }});

        // -- Create a new message --
        Message msg = new MimeMessage(session);

        // -- Set the FROM and TO fields --
        msg.setFrom(new InternetAddress(EmailConfig.emailConfig.userName));
        msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(toUser,false));
        msg.setSubject(title);
        msg.setText(content);
        msg.setSentDate(new Date());
        Transport.send(msg);

    }

    /**
     * 邮箱配置类 使用163邮箱
     * 定期刷新邮箱配置文件,实现管理员可以修改邮箱地址的需求
     *
     * 单例模式
     * @author zp
     */
    private static class EmailConfig {

        private String userName;//邮箱
        private String password;//邮箱授权码
        private String mailSmtpHost;//邮箱服务器

        private long time;

        private static final EmailConfig emailConfig = new EmailConfig();

        private EmailConfig(){
            if(getConfig() == false){
                System.out.println("邮箱配置文件加载失败");
            }
            time = System.currentTimeMillis();
        }

        /**
         * 更新配置文件
         * @return
         */
        public boolean updateConfigFile(){
            if(System.currentTimeMillis() - time >= UPDATE_MINUTES*60*1000){//时间超过 分钟,更新配置文件
                return getConfig();
            }
            return true;
        }

        /**
         * 刷新配置文件
         * @return
         */
        private boolean getConfig(){
            Properties prop = new Properties();

            try {
                prop.load(new FileInputStream(EmailUtils.CONFIG_FILE_LOCATION));

                if(prop.getProperty("userName") == null || prop.getProperty("userName").equals("") ||
                        prop.getProperty("password") == null || prop.getProperty("password").equals("") ||
                        prop.getProperty("mailSmtpHost") == null || prop.getProperty("mailSmtpHost").equals("")){
                    return false;
                }

                userName = prop.getProperty("userName");
                password = prop.getProperty("password");
                mailSmtpHost = prop.getProperty("mailSmtpHost");

            } catch(IOException e) {
                e.printStackTrace();
                return false;
            }
            return true;
        }
    }


    public static void main(String[] args) throws Exception {
        sendMail("1802226517@qq.com","哎呀","你好");
    }
}

配置文件参考:

该文件路径:/Users/spz/work/project/kuyun_brn/src/main/resources/email.properties,注意要和代码里CONFIG_FILE_LOCATION的配置一致。

# Email config file. see EmailUtils.java

# 使用163邮箱,不需要改动
mailSmtpHost=smtp.163.com

# 邮箱账号
userName=xxxxxxxxxxx@163.com

# 授权码,需要登录163邮箱,在设置里设置授权码。授权码用于替代密码
password=xxxxxxxxx

个人公众号,定期分享各种技术干货,欢迎扫码关注! 

公众号二维码

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值