Java发送邮件验证码

package org.jeecg.modules.system.util;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class MailUtils {

    public static void toMail(String email,String code) {
        String from = "";// 发件人电子邮箱
        String host = "smtp.163.com"; // 指定发送邮件的主机smtp.qq.com(QQ)|smtp.163.com(网易)

        Properties properties = System.getProperties();// 获取系统属性

        properties.setProperty("mail.smtp.host", host);// 设置邮件服务器
        properties.setProperty("mail.smtp.auth", "true");// 打开认证

        try {
            //QQ邮箱需要下面这段代码,163邮箱不需要
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);


            // 1.获取默认session对象
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("", ""); // 发件人邮箱账号、授权码
                }
            });

            // 2.创建邮件对象
            Message message = new MimeMessage(session);
            // 2.1设置发件人
            message.setFrom(new InternetAddress(from));
            // 2.2设置接收人
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
            // 2.3设置邮件主题
            message.setSubject("修改密码");
            // 2.4设置邮件内容
            String content = "\n" +
                    "    \n" +
                    "    \n" +
                    "    \n" +
                    "    \n" +
                    "    \n" +
                    "\n" +
                    "\n" +
                    "\n"+"    \n"+"    \n"+"        \n"+"    \n"+"    \n"+"
\n" + "
\n" + " \n"+" \n"+"
\n"
+ "
\n"
+ "
\n" + "
\n" + " 尊敬的用户:您好!\n" + " \n" + " 您的验证码是:"+code+",以完成操作。\n" + " \n" + "
\n"
+ "
\n" + " \n" + "

\n" + " 注意:此操作可能会修改您的密码。如非本人操作,请及时登录并修改密码以保证帐户安全\n" + "
(工作人员不会向你索取此验证码,请勿泄漏!)\n"
+ "

\n"
+ "
\n" + "
\n"
+ "
\n"
+ "
\n" + "
\n" + "

此为系统邮件,请勿回复
\n" + " 请保管好您的邮箱,避免账号被他人盗用\n" + "

\n"
+ "

公司名称

\n"
+ "
\n"
+ "
\n"
+ "
\n"
+ ""; message.setContent(content, "text/html;charset=UTF-8"); // 3.发送邮件 Transport.send(message); System.out.println("邮件成功发送!"); } catch (Exception e) { e.printStackTrace(); } } }
//调用
 MailUtils.toMail(email, code);

你可能感兴趣的:(Java基础,JavaWeb基础)