[Java]smtp发送邮件,解决中文乱码,发送HTML邮件

2021-03-30 2122点热度 0人点赞 1条评论

前言

本篇介绍如果利用javamail发送邮件

实现

引入JavaMail依赖

如果是Maven,加入pom.xml:

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

如果是Gradle,加入build.gradle

implementation("com.sun.mail:javax.mail:1.6.2")

新建MailUtils工具类:

目前使用的邮件服务器基本上都是需要验证的,所以使用了EmailAutherticator extends Authenticator做认证

subject主题用MimeUtility编码过,解决中文乱码问题。

package com.terrynow.test;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.util.Date;
import java.util.Properties;

/**
 * @author Terry E-mail: yaoxinghuo at 126 dot com
 * @date 2021-03-30 2:09:15
 */
public class MailUtils {
    private String host;//邮件服务器smtp地址
    private String username;//发送邮件的账号
    private String password;//发送邮件的密码
    private String from;//发件人的email地址
    private String fromnick;//发件人的昵称

    /**
     *
     * @param host 邮件服务器smtp地址
     * @param username 发送邮件的账号
     * @param password 发送邮件的密码
     * @param from 发件人的email地址
     * @param fromnick 发件人的昵称
     */
    public MailUtils(String host, String username, String password, String from, String fromnick) {
        this.host = host;
        this.username = username;
        this.password = password;
        this.from = from;
        this.fromnick = fromnick;
    }

    public void sendMail(String toName, String toAddress, String subject, String body) throws Exception {
        Properties props = new Properties();
        Authenticator auth = new EmailAutherticator();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");
//        props.put("mail.smtp.port", "465");//smt端口默认25,如果是不是默认端口,可以另外设置

        Session session = Session.getDefaultInstance(props, auth);
        // 设置session,和邮件服务器进行通讯。
        MimeMessage message = new MimeMessage(session);
        message.setSubject(MimeUtility.encodeText(subject)); // 设置邮件主题
        message.setText(body); // 设置邮件正文
        message.setContent("", "text/html;charset=utf-8");

        message.setSentDate(new Date()); // 设置邮件发送日期
        message.setFrom(new InternetAddress(from, fromnick)); // 设置邮件发送者的地址
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress, toName));
        Transport.send(message);
    }

    public void sendHtmlMail(String toName, String toAddress, String subject, String html) throws Exception {
        Properties props = new Properties();
        Authenticator auth = new EmailAutherticator();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");
//        props.put("mail.smtp.port", "465");//smt端口默认25,如果是不是默认端口,可以另外设置

        Session session = Session.getDefaultInstance(props, auth);
        // 设置session,和邮件服务器进行通讯。
        MimeMessage message = new MimeMessage(session);
        message.setSubject(MimeUtility.encodeText(subject)); // 设置邮件主题
        message.setContent(html, "text/html;charset=utf-8"); // 设置HTML邮件正文

        message.setSentDate(new Date()); // 设置邮件发送日期
        message.setFrom(new InternetAddress(from, fromnick)); // 设置邮件发送者的地址
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress, toName));
        Transport.send(message);
    }

    /**
     * 用来进行服务器对用户的认证
     */
    class EmailAutherticator extends Authenticator {
        public EmailAutherticator() {
            super();
        }

        public EmailAutherticator(String user, String pwd) {
            super();
            username = user;
            password = pwd;
        }

        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    }

}

 

测试发送邮件:

//填入邮件服务器的基本信息,如smtp地址,账号,密码等
MailUtils u = new MailUtils("smtpdm.aliyun.com", "[email protected]", "password",
        "[email protected]", "Terry");
//发送邮件
u.sendMail("service", "[email protected]", "中文主题", "中文内容");

//测试发送HTML的邮件(样式都建议写在style里)
String html = "<body style=\"color: #666; font-size: 14px; font-family: 'Open Sans',Helvetica,Arial,sans-serif;\">" +
"<div style='font-size:18px;font-weight:600;color:red'>测试HTML</div>"+
"</body>";
u.sendHtmlMail("service", "[email protected]", "中文主题", html);

 

admin

这个人很懒,什么都没留下

文章评论

  • MutAppata

    Cialis Jfficr Eqqqrb order cialis online without prescription Cialis site de vente de cialis Vuhpby

    2022-06-09
  • 您需要 登录 之后才可以评论