【更新】Java發送郵件:個人郵箱+企業郵箱+Android

這次把兩種情況仔細說一下,因爲好多人問啦。

第一種:企業郵箱

這裏在這一篇已經說的很清楚了,這次不過是建立個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

# 發件郵箱
[email protected]
# 不需要密碼
#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>");
    }
}

  

 

 

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章