栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

发送邮件工具类

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

发送邮件工具类

准备::Maven项目

1.导入jar包:


    com.sun.mail
    javax.mail
    1.6.2

2.编写 MailUtil工具类

package com.wanshi.spring.utils;

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


public class MailUtil {

    public static void sendTextMail(final String to, final String subject,final String content){
        String host = "smtp.163.com";
        String user = ""; //你的邮箱账号
        String password= ""; //你的邮箱授权码

        try {
            sendTextMail(host, user, password, to, subject, content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void sendTextMail(final String host, final String user, final String password,
                            final String to,  final String subject, final String content) throws Exception {
        // 相关的属性
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.timeout", "20000");

        // 设置 电子邮箱和密码,做发送邮件的授权
        Authenticator auth = new Authenticator() {
            @Override
            protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, password);
            }
        };
        Session session = Session.getInstance(props, auth);

        // 定义要发送邮件的内容
        MimeMessage msg = new MimeMessage(session);
        // 设置发送放的电子邮箱
        msg.setFrom(new InternetAddress(user));
        // 接收方的电子邮箱
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));

        // 标题,主题
        msg.setSubject(subject);

        // 发送的文本内容
        msg.setText(content);

        // 保存邮件
        msg.saveChanges();
        Transport.send(msg, msg.getAllRecipients());
    }


}

3.测试类:

import com.wanshi.spring.utils.MailUtil;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class test {

    @Test
    public void test(){
        String content = ""; //内容
        MailUtil.sendTextMail("要接收的邮箱", "标题", content);
    }

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/592099.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号