Java实现发送邮件(JavaMail代码)

导读:本篇文章讲解 Java实现发送邮件(JavaMail代码),文章出自:https://blog.csdn.net/weixin_43316702/article/details/114506561希望对大家有帮助,欢迎收藏,转发!站点地址:www.javazhiyin.com.com

>>强大,10k+点赞的 SpringBoot 后台管理系统竟然出了详细教程!

JavaMail实现发送邮件,需要有一个发送邮件的主邮箱,且主邮箱需要开启开启POP3/SMTP协议(一般用qq邮箱,其他邮箱可能会有点问题)
代码如下:直接使用即可

import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.sun.mail.util.MailSSLSocketFactory;

/**
 * JavaMail发送邮件: java版本-与web无关
 * 前提是QQ邮箱里帐号设置要开启POP3/SMTP协议
 */
public class JavaMail {
    public void send(HttpServletRequest request,String receiver) throws Exception {
        Properties prop = new Properties();
        // 开启debug调试,以便在控制台查看
        prop.setProperty("mail.debug", "true");
        // 设置邮件服务器主机名
        prop.setProperty("mail.host", "smtp.qq.com");
        // 发送服务器需要身份验证
        prop.setProperty("mail.smtp.auth", "true");
        // 发送邮件协议名称
        prop.setProperty("mail.transport.protocol", "smtp");
        // 开启SSL加密,否则会失败
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);
        // 创建session
        Session session = Session.getInstance(prop);
        // 通过session得到transport对象
        Transport ts = session.getTransport();
        // 连接邮件服务器:邮箱类型,帐号,POP3/SMTP协议授权码 163使用:smtp.163.com
        ts.connect("smtp.qq.com", "正确的qq号", "tqejtlkfdgnjcaec");//授权码需要自己弄
        // 创建邮件
        Message message = createSimpleMail(request,session,receiver);
        // 发送邮件
        ts.sendMessage(message, message.getAllRecipients());
        ts.close();
        //System.out.println("code:"+request.getSession().getAttribute("code"));
    }

    /**
     * @Method: createSimpleMail
     * @Description: 创建一封只包含文本的邮件
     */
    public static MimeMessage createSimpleMail(HttpServletRequest request,Session session,String receiver) throws Exception {
        //  获取6为随机验证码
        String[] letters = new String[] {
                "q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m",
                "A","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M",
                "0","1","2","3","4","5","6","7","8","9"};
        String stringBuilder ="";
        for (int i = 0; i < 6; i++) {
            stringBuilder = stringBuilder + letters[(int)Math.floor(Math.random()*letters.length)];
        }
        HttpSession httpSession = request.getSession(true);
        httpSession.setAttribute("code",stringBuilder);
        //设置超时,另外的方法,没贴出来
        //TimeOut o = new TimeOut();
        //o.SessionOut(request,"code",60);
        // 创建邮件对象
        MimeMessage message = new MimeMessage(session);
        // 指明邮件的发件人(主邮箱)
        message.setFrom(new InternetAddress("****@qq.com"));
        // 指明邮件的收件人,发件人和收件人如果是一样的,那就是自己给自己发
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(receiver));
        // 邮件的标题
        message.setSubject("【**主题】");
        // 邮件的文本内容
        message.setContent("欢迎您使用【***】,验证码为(一分钟有效):"+stringBuilder+",请勿回复此邮箱", "text/html;charset=UTF-8");
        // 返回创建好的邮件对象
        return message;
    }

//    public static void main(String[] args) {
//        JavaMail j = new JavaMail();
//        try {
//            j.send("chen190427@126.com");//需要发送到的邮箱
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}

发送完后可以设置session保存,然后验证,发送后可以设置时长多久清除session,具体的就不列出来了,发送邮箱的代码可以直接进行单元测试使用。谢谢学习!