java发送邮件

发布时间:2024年01月19日

发送邮件工具类:
EmailUtils:


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

/**
 * 发送邮件
 */
@Component
public class EmailUtils {
    // 发件人邮箱账号密码
    @Value("${email.account}")
    private String emailAccount;
    @Value("${email.password}")
    private String emailPassword;

    // 发件人邮箱的 SMTP 服务地址
    @Value("${email.smtphost}")
    private String emailSMTPHost;

    /**
     * 
     * @param receiveMailAccount 收件人邮箱
     * @param subject 邮件主题
     * @param text 邮件内容
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     */
    public void sendEmail(String receiveMailAccount,String subject,String text) throws UnsupportedEncodingException, MessagingException {
        Transport transport = null;
        try {
            // 1.创建参数配置,用于链接邮件服务器的参数配置
            Properties props = new Properties();
            props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议
            props.setProperty("mail.smtp.host", emailSMTPHost);
            props.setProperty("mail.smtp.auth", "true"); // 需要请求认证

            // 2.根据配置创建会话对象,用户和邮件服务器交互
            Session session = Session.getDefaultInstance(props);
//            session.setDebug(true); // 设置debug模式,可以查看详细的发送Log

            // 3.创建一封邮件
            MimeMessage message = createMimeMessage(session, subject,emailAccount, receiveMailAccount, text);

            // 4.根据Session获取邮件传输对象
            transport = session.getTransport();

            // 5.使用邮箱账号和密码链接邮件服务器,这里认证的邮箱必须与message中的发件人邮箱一致,否则报错
            transport.connect(emailAccount, emailPassword);

            // 6.发送邮件,message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
            transport.sendMessage(message, message.getAllRecipients());
        } catch (UnsupportedEncodingException e) {
           throw e;
        } catch (MessagingException e) {
           throw e;
        } finally {
            // 7.关闭链接
            if (transport != null) {
                try {
                    transport.close();
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private String getExceptionText(Exception ex) {
        StringBuilder sb = new StringBuilder();
        sb.append(ex.getMessage());
        StackTraceElement[] trace = ex.getStackTrace();
        for (StackTraceElement traceElement : trace) {
            sb.append("\tat " + traceElement);
        }
        return sb.toString();
    }

    private MimeMessage createMimeMessage(Session session, String subject,String emailAccount, String receiveMailAccount, String text) throws UnsupportedEncodingException, MessagingException {
        MimeMessage message = new MimeMessage(session);
        // 发件人
        message.setFrom(new InternetAddress(emailAccount));
        // 收件人
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMailAccount));
        // 邮件主题
        message.setSubject(subject, "utf-8");
        // 邮件正文
        message.setContent(text, "text/html;charset=utf-8");
        // 保存设置
        message.saveChanges();
        return message;
    }
}

配置文件:

# 发件人邮箱 (原来发件人和收件人可以使用同一个邮箱,自己给自己发)
email.account=xxx
## 企业邮箱这里用的密码,个人邮箱用授权码
email.password=xxx
# 发件人邮箱的 SMTP 服务地址
# 这里是微信企业邮箱
email.smtphost=smtp.exmail.qq.com
# 邮件收件人
recieivedEmail=xxx@.com

常用的smtp服务器:
微信企业邮箱:
smtp.exmail.qq.com
qq邮箱:
smtp.qq.com
163邮箱:
smtp.163.com

测试:

String sendEmail = "";
        String text = "";
        String receivedEmail = "";
        try {
            String subject = "邮件主题";
            StringBuilder content = new StringBuilder("Mail:").append(sendEmail);
            content.append("<br/>").append("content:").append(text);
            emailUtils.sendEmail(receivedEmail,subject, content.toString());
        } catch (Exception e) {
            log.error("sendHSF request:{},error:{}", request, e);
        }
文章来源:https://blog.csdn.net/flower_CSDN/article/details/135692296
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。