首页 > 技术文章 > 【更新】Java发送邮件:个人邮箱(QQ & 网易163)+企业邮箱+Android

LUA123 2019-07-29 19:36 原文

这次把两种情况仔细说一下,因为好多人问啦。

第一种:企业邮箱

这里在这一篇已经说的很清楚了,这次不过是建立个maven工程,引入了最新的javamail依赖,代码优化了一下。直接上代码

pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.demo</groupId>
    <artifactId>javamail-update</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/javax.mail/javax.mail-api -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>javax.mail-api</artifactId>
            <version>1.6.2</version>
            <scope>provided</scope>
        </dependency>

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

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

 

CompanyEmail.properties

e.account=***@***.cn
e.pass=***
e.host=smtp.exmail.qq.com
e.port=465
e.protocol=smtp

  

SendEmailCompanyUtils

package com.demo;

import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.StringUtils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;

/**
 * 企业邮箱
 */
public class SendEmailCompanyUtils {

    private static String account;	//登录用户名
    private static String pass;		//登录密码
    private static String host;		//服务器地址(邮件服务器)
    private static String port;		//端口
    private static String protocol; //协议

    static{
        Properties prop = new Properties();
//		InputStream instream = ClassLoader.getSystemResourceAsStream("CompanyEmail.properties");//测试环境
        try {
//			prop.load(instream);//测试环境
            prop = PropertiesLoaderUtils.loadAllProperties("CompanyEmail.properties");//生产环境
        } catch (IOException e) {
            System.out.println("加载属性文件失败");
        }
        account = prop.getProperty("e.account");
        pass = prop.getProperty("e.pass");
        host = prop.getProperty("e.host");
        port = prop.getProperty("e.port");
        protocol = prop.getProperty("e.protocol");
    }

    static class MyAuthenticator extends Authenticator {
        String u = null;
        String p = null;

        private MyAuthenticator(String u,String p){
            this.u=u;
            this.p=p;
        }
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(u,p);
        }
    }

    private String to;	//收件人
    private String subject;	//主题
    private String content;	//内容
    private String fileStr;	//附件路径

    public SendEmailCompanyUtils(String to, String subject, String content, String fileStr) {
        this.to = to;
        this.subject = subject;
        this.content = content;
        this.fileStr = fileStr;
    }

    public void send(){
        Properties prop = new Properties();
        //协议
        prop.setProperty("mail.transport.protocol", protocol);
        //服务器
        prop.setProperty("mail.smtp.host", host);
        //端口
        prop.setProperty("mail.smtp.port", port);
        //使用smtp身份验证
        prop.setProperty("mail.smtp.auth", "true");
        //使用SSL,企业邮箱必需!
        //开启安全协议
        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            prop.put("mail.smtp.ssl.enable", "true");
            prop.put("mail.smtp.ssl.socketFactory", sf);
        } catch (GeneralSecurityException e1) {
            e1.printStackTrace();
        }

        Session session = Session.getDefaultInstance(prop, new MyAuthenticator(account, pass));
        session.setDebug(true);
        MimeMessage mimeMessage = new MimeMessage(session);
        try {
            //发件人
            mimeMessage.setFrom(new InternetAddress(account,"XXX"));		//可以设置发件人的别名
            //mimeMessage.setFrom(new InternetAddress(account));	//如果不需要就省略
            //收件人
            mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            //主题
            mimeMessage.setSubject(subject);
            //时间
            mimeMessage.setSentDate(new Date());
            //容器类,可以包含多个MimeBodyPart对象
            Multipart mp = new MimeMultipart();

            //MimeBodyPart可以包装文本,图片,附件
            MimeBodyPart body = new MimeBodyPart();
            //HTML正文
            body.setContent(content, "text/html; charset=UTF-8");
            mp.addBodyPart(body);

            //添加图片&附件
            if(!StringUtils.isEmpty(fileStr)){
                body = new MimeBodyPart();
                body.attachFile(fileStr);
                mp.addBodyPart(body);
            }

            //设置邮件内容
            mimeMessage.setContent(mp);
            //仅仅发送文本
            //mimeMessage.setText(content);
            mimeMessage.saveChanges();
            Transport.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  

CompanySending

package com.demo;

/**
 * 发送线程
 */
public class CompanySending implements Runnable {

    private String to;	//收件人
    private String subject;	//主题
    private String content;	//内容
    private String fileStr;	//附件路径

    public CompanySending(String to, String subject, String content, String fileStr) {
        this.to = to;
        this.subject = subject;
        this.content = content;
        this.fileStr = fileStr;
    }

    public void run() {
        SendEmailCompanyUtils sendEmail = new SendEmailCompanyUtils(to, subject, content, fileStr);
        sendEmail.send();
    }
}

  

CompanySendingPool

package com.demo;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 发送线程池
 */
public class CompanySendingPool {
    private CompanySendingPool() {
    }
    private static class Inner{
        private static CompanySendingPool instance = new CompanySendingPool();
    }

    public static CompanySendingPool getInstance(){
        return Inner.instance;
    }

    /**
     * 核心线程数:5
     * 最大线程数:10
     * 时间单位:秒
     * 阻塞队列:10
     */
    private static ThreadPoolExecutor executor = new ThreadPoolExecutor(
            5,
            10,
            0L,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(10));

    public CompanySendingPool addThread(CompanySending sending){
        executor.execute(sending);
        return getInstance();
    }

    public void shutDown(){
        executor.shutdown();
    }
}

  

测试

package com.demo;

public class MyTest {

    public static void main(String[] args) {
        CompanySendingPool pool = CompanySendingPool.getInstance();
        pool.addThread(new CompanySending("***@qq.com", "AAA", createEmail().toString(), "file/1.jpg")).shutDown();
    }

    private static StringBuilder createEmail() {
        return new StringBuilder("<!DOCTYPE html><html><head><meta charset='UTF-8'><title>快来买桃子</title><style type='text/css'>        .container{            font-family: 'Microsoft YaHei';            width: 600px;            margin: 0 auto;            padding: 8px;            border: 3px dashed #db303f;            border-radius: 6px;        }        .title{            text-align: center;            color: #db303f;        }        .content{            text-align: justify;            color: #717273;            font-weight: 600;        }        footer{            text-align: right;            color: #db303f;            font-weight: 600;            font-size: 18px;        }</style></head><body><div class='container'><h2 class='title'>好吃的桃子</h2><p class='content'>桃子含有维生素A、维生素B和维生素C,儿童多吃桃子可使身体健康成长,因为桃子含有的多种维生索可以直接强化他们的身体和智力。</p><footer>联系桃子:11110000</footer></div></body></html>");
    }
}

  

 

第二种:个人邮箱

--

--

--

--

 --

记下授权码,一毛钱呢。下面上代码

PersonalEmail.properties

# 发件邮箱
e.account=from@qq.com
# 不需要密码
#e.pass=***
e.host=smtp.qq.com
e.port=25
e.protocol=smtp
# 授权码
e.authorizationCode=fvwmtg***bchb

  

SendEmailPersonalUtils

package com.demo;

import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.StringUtils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

/**
 * 关于授权码:https://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
 * 个人邮箱
 */
public class SendEmailPersonalUtils {

    private static String account;	//登录用户名
    private static String pass;		//登录密码
    private static String host;		//服务器地址(邮件服务器)
    private static String port;		//端口
    private static String protocol; //协议

    static{
        Properties prop = new Properties();
//		InputStream instream = ClassLoader.getSystemResourceAsStream("PersonalEmail.properties");//测试环境
        try {
//			prop.load(instream);//测试环境
            prop = PropertiesLoaderUtils.loadAllProperties("PersonalEmail.properties");//生产环境
        } catch (IOException e) {
            System.out.println("加载属性文件失败");
        }
        account = prop.getProperty("e.account");
        // 个人邮箱需要授权码,而不是密码。在密码的位置上填写授权码
        pass = prop.getProperty("e.authorizationCode");
        host = prop.getProperty("e.host");
        port = prop.getProperty("e.port");
        protocol = prop.getProperty("e.protocol");
    }

    static class MyAuthenticator extends Authenticator {
        String u = null;
        String p = null;

        private MyAuthenticator(String u,String p){
            this.u=u;
            this.p=p;
        }
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(u,p);
        }
    }

    private String to;	//收件人
    private String subject;	//主题
    private String content;	//内容
    private String fileStr;	//附件路径

    public SendEmailPersonalUtils(String to, String subject, String content, String fileStr) {
        this.to = to;
        this.subject = subject;
        this.content = content;
        this.fileStr = fileStr;
    }

    public void send(){
        Properties prop = new Properties();
        //协议
        prop.setProperty("mail.transport.protocol", protocol);
        //服务器
        prop.setProperty("mail.smtp.host", host);
        //端口
        prop.setProperty("mail.smtp.port", port);
        //使用smtp身份验证
        prop.setProperty("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(prop, new SendEmailPersonalUtils.MyAuthenticator(account, pass));
        session.setDebug(true);
        MimeMessage mimeMessage = new MimeMessage(session);
        try {
            //发件人
            mimeMessage.setFrom(new InternetAddress(account,"XXX"));		//可以设置发件人的别名
            //mimeMessage.setFrom(new InternetAddress(account));	//如果不需要就省略
            //收件人
            mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            //主题
            mimeMessage.setSubject(subject);
            //时间
            mimeMessage.setSentDate(new Date());
            //容器类,可以包含多个MimeBodyPart对象
            Multipart mp = new MimeMultipart();

            //MimeBodyPart可以包装文本,图片,附件
            MimeBodyPart body = new MimeBodyPart();
            //HTML正文
            body.setContent(content, "text/html; charset=UTF-8");
            mp.addBodyPart(body);

            //添加图片&附件
            if(!StringUtils.isEmpty(fileStr)){
                body = new MimeBodyPart();
                body.attachFile(fileStr);
                mp.addBodyPart(body);
            }

            //设置邮件内容
            mimeMessage.setContent(mp);
            //仅仅发送文本
            //mimeMessage.setText(content);
            mimeMessage.saveChanges();
            Transport.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  

PersonalSending

package com.demo;

/**
 * 发送线程
 */
public class PersonalSending implements Runnable {
    private String to;	//收件人
    private String subject;	//主题
    private String content;	//内容
    private String fileStr;	//附件路径

    public PersonalSending(String to, String subject, String content, String fileStr) {
        this.to = to;
        this.subject = subject;
        this.content = content;
        this.fileStr = fileStr;
    }

    public void run() {
        SendEmailPersonalUtils sendEmail = new SendEmailPersonalUtils(to, subject, content, fileStr);
        sendEmail.send();
    }
}

  

PersonalSendingPool

package com.demo;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 发送线程池
 */
public class PersonalSendingPool {

    private PersonalSendingPool() {
    }
    private static class Inner{
        private static PersonalSendingPool instance = new PersonalSendingPool();
    }

    public static PersonalSendingPool getInstance(){
        return PersonalSendingPool.Inner.instance;
    }

    /**
     * 核心线程数:5
     * 最大线程数:10
     * 时间单位:秒
     * 阻塞队列:10
     */
    private static ThreadPoolExecutor executor = new ThreadPoolExecutor(
            5,
            10,
            0L,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(10));

    public PersonalSendingPool addThread(PersonalSending sending){
        executor.execute(sending);
        return getInstance();
    }

    public void shutDown(){
        executor.shutdown();
    }
}

  

测试:

package com.demo;

public class MyTest {

    public static void main(String[] args) {
        PersonalSendingPool pool = PersonalSendingPool.getInstance();
        pool.addThread(new PersonalSending("***@qq.com", "BBB", createEmail().toString(), "file/1.jpg")).shutDown();
    }

    private static StringBuilder createEmail() {
        return new StringBuilder("<!DOCTYPE html><html><head><meta charset='UTF-8'><title>快来买桃子</title><style type='text/css'>        .container{            font-family: 'Microsoft YaHei';            width: 600px;            margin: 0 auto;            padding: 8px;            border: 3px dashed #db303f;            border-radius: 6px;        }        .title{            text-align: center;            color: #db303f;        }        .content{            text-align: justify;            color: #717273;            font-weight: 600;        }        footer{            text-align: right;            color: #db303f;            font-weight: 600;            font-size: 18px;        }</style></head><body><div class='container'><h2 class='title'>好吃的桃子</h2><p class='content'>桃子含有维生素A、维生素B和维生素C,儿童多吃桃子可使身体健康成长,因为桃子含有的多种维生索可以直接强化他们的身体和智力。</p><footer>联系桃子:11110000</footer></div></body></html>");
    }
}

  

 

 

如果是网易邮箱

进入设置

点击开启

不得不说,网易良心啊,不用短信费,输入正确的验证码之后

输入授权码(自己定义)

到此授权码设置完成。

然后呢,只需要打开PersonalEmail.properties属性文件。修改三个地方即可。

收到的

 

GitHub地址:https://github.com/Mysakura/JavaMail-Update

第三种:Android(有Android专门支持的jar包)

 https://javaee.github.io/javamail/#JavaMail_for_Android

在中央仓库里也可以看见哦

https://mvnrepository.com/artifact/com.sun.mail/android-mail

https://mvnrepository.com/artifact/com.sun.mail/android-activation

 

推荐阅读