Java发送邮件那些事

需求

最近在由于项目需求需要用到邮箱验证,因此在这里分享一下Java如何用代码实现邮箱发送信息到用户手里(这里以qq邮箱为例)

最终效果

这里展示一下发送到用户手里的最终效果


效果

那么如何实现呢?

1. 开通服务

  • 登录到自己的qq邮箱中
  • 点击头部的”设置“按钮
  • 点击二级目录“账户”中拉到下部,这POP3/SMTP服务IMAP/SMTP服务这两项勾上
    开启发送服务
  • 开启后记录验证后的校验串,供后续代码使用

2. 导入依赖



  org.springframework
  spring-context-support
  5.2.4.RELEASE




  com.sun.mail
  javax.mail
  1.6.1

3. 编写MailUtils工具类

这这里解释一下类里面看两个方法:

sendEmail() 为发送的方法,参数有
toEmailAddress:用户邮箱
emailTitle:邮件标题
emailContent:发送内容

DLYZ() 方法则为HTML模板,参数只有一个,就是验证码code。可以根据自定义HTML发送,当然这里不建议引入css文件和js文件,因为邮箱服务器会在发送后屏蔽掉这些文件


下面代码过多,自行品味

public class MailUtils {

    public static void sendEmail(String toEmailAddress, String emailTitle, StringBuffer emailContent) throws GeneralSecurityException, MessagingException {
        Properties props = new Properties();
//开启debug调试
        props.setProperty("mail.debug", "false");
//发送服务器需要身份验证
        props.setProperty("mail.smtp.auth", "true");
//设置邮件服务器主机名
        props.setProperty("mail.host", "smtp.qq.com");
//发送邮件协议名称
        props.setProperty("mail.transport.protocol", "smtp");
//创建MailSSLSocketFactory
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);

//创建会话
        Session session = Session.getInstance(props);

//发送的消息,基于观察者模式进行设计的
        Message msg = new MimeMessage(session);
//设置发送标题
        msg.setSubject(emailTitle);

//设置发送内容
//使用StringBuilder,因为StringBuilder加载速度会比String快,而且线程安全性也不错
        StringBuilder builder = new StringBuilder();
        builder.append("\n" + emailContent);

//发送普通文本内容
        //msg.setText(builder.toString());
//发送带html的内容(由于需要发送HTML信息,故选这个)
        msg.setContent(builder.toString(),"text/html;charset=utf-8");     
   
        msg.setFrom(new InternetAddress("发送者邮箱"));
        Transport transport = session.getTransport();
        transport.connect("smtp.qq.com", "发送者邮箱", "校验串");

        transport.sendMessage(msg, new Address[]{new InternetAddress(toEmailAddress)});
        transport.close();
    }


    //登录验证码HTML消息模板
    public StringBuffer DLYZ(String code){
        StringBuffer dlyz =new StringBuffer();

        dlyz.append("\n" +
                "
\n" + "
\n" + "
\n" + "
\n" + "
OA系统
\n" + "
\n" + "
\n" + "
\n" + "

Hi,

\n" + "

欢迎使用XXXXX-XXXXOA系统,您的验证码为:"+code+" (5分钟内有效),为了保证您的帐户安全,请勿向任何人提供此验证码。感谢您使用!

\n" + "
\n" + "
本邮件由系统自动发送,请勿直接回复
\n" + "
\n" + " \n" + " \n" + " \n" + " \n" + "官方网站:http://000.00.00.00:8088\n" + " \n" + " \n" + " \n" + "
\n" + "管理员邮箱:
[email protected]\n" + " \n" + "
\n" + "
\n" + "
\n" + "\n"); return dlyz; } }

4. 测试发送

    @Test
    public void testMailTemplate() throws GeneralSecurityException, MessagingException {
        MailUtils mailUtils = new MailUtils();
        mailUtils.sendEmail("某某某@qq.com","测试邮件发送",mailUtils.DLYZ("666666"));
    }

结果:

效果

OK,大功告成!

你可能感兴趣的:(Java发送邮件那些事)