Azkaban思考题:使用java代码编写一个任务,给别人发邮件


https://blog.csdn.net/m0_67840539/article/details/130655325

导入包:

<dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.6.2</version>
        </dependency>
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>javax.mail-api</artifactId>
            <version>1.4.7</version>
        </dependency>

编写代码:

package com.email;

/***
 * @Date(时间)2023-05-12
 * @Author xx
 *
 *
 *
 * 发送邮件
 */
public class Email_Code {

    //测试一下
    public static void main(String[] args) throws Exception {

        for (int i = 0; i < 10; i++) {
            EmailUtils.sendEmail("18638147931@163.com","2844408713@qq.com","赛哥","六哥","某某大厦301房间等你","暗号:三长两短");
        }

    }


}

工具类代码

package com.email;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

public class EmailUtils {

    public static void sendEmail(String fromAccount,String toAccount,String fromName,String toName,String title,String content) throws Exception {

        // 参数配置,⽤于连接邮件服务器
        Properties props = new Properties();
        // 使⽤协议
        props.setProperty("mail.transport.protocol", "smtp");
        // 发件⼈邮箱的 SMTP 服务器地址
        props.setProperty("mail.smtp.host", "smtp.163.com");
        // 需要请求认证
        props.setProperty("mail.smtp.auth", "true");
        // 创建会话对象,⽤于与邮箱服务器交互
        Session session = Session.getInstance(props);
        // 设置为debug模式,在控制台中可以查看详细的发送⽇志
        session.setDebug(true);

        // 1.创建邮件对象
        MimeMessage message = new MimeMessage(session);
        // 2.设置发件⼈,其中 InternetAddress 有三个参数,分别为:邮箱,显示的昵称,昵称的字符集编码
        message.setFrom(new InternetAddress(fromAccount, fromName, "UTF-8"));

        // 3.设置收件⼈ - MimeMessage.RecipientType.TO
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(toAccount ,toName, "UTF-8"));

        // 7.设置邮件主题
        message.setSubject(title,"UTF-8");

        // 8.设置邮件正⽂内容,指定格式为HTML格式
        message.setContent(content, "text/html;charset=UTF-8");
        // 9.设置显示发件时间
        message.setSentDate(new Date());

        // 10.保存设置
        message.saveChanges();

        // 根据 Session 获取邮件传输对象
        Transport transport = session.getTransport();
        // 连接邮件服务器
        transport.connect("18638147931@163.com", "MAGBDQDGKEHCBVQA");
        // 发送邮件
        transport.sendMessage(message, message.getAllRecipients());
        // 关闭连接
        transport.close();
    }
}