继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

[Java工具] 邮件发送工具

慕码人8056858
关注TA
已关注
手记 1092
粉丝 350
获赞 1320

更新

  • 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



作者:萌璐琉璃
链接:https://www.jianshu.com/p/b58b7e2a1dac


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP