java網絡編程(5):SMTP

第0章:簡介

        SMTP(Simple Mail Transfer Protocol)即簡單郵件傳輸協議,它是一組用於由源地址到目的地址傳送郵件的規則,由它來控制信件的中轉方式。SMTP協議屬於TCP/IP協議族,它幫助每臺計算機在發送或中轉信件時找到下一個目的地。通過SMTP協議所指定的服務器,就可以把E-mail寄到收信人的服務器上了,整個過程只要幾分鐘。SMTP服務器則是遵循SMTP協議的發送郵件服務器,用來發送或中轉發出的電子郵件Windows Server 2003默認情況下是沒有安裝POP3和SMTP服務組件的,因此我們要手工添加。
(來源:百度百科)

第0節:SMTP工作原理

SMTP要經過建立連接、傳送郵件和釋放連接3個階段。具體爲:

(1)建立TCP連接。
(2)客戶端向服務器發送HELLO命令以標識發件人自己的身份,然後客戶端發送MAIL命令。
(3)服務器端以OK作爲響應,表示準備接收。
(4)客戶端發送RCPT命令。
(5)服務器端表示是否願意爲收件人接收郵件。
(6)協商結束,發送郵件,用命令DATA發送輸入內容。
(7)結束此次發送,用QUIT命令退出。

第1節:各類郵箱服務器地址


一般地  郵箱 POP3 服務器(端口110) SMTP 服務器(端口25)

163免費郵箱的郵件服務器地址
   接收郵件(pop、IMAP或HTTP)服務器:字段中輸入   pop.163.com。
   發送郵件服務器(SMTP):             字段中輸入   smtp.163.com
在屬性設置窗口中,選擇“服務器”選項卡,勾選“我的服務器需要身份驗證。如果你希望在服務器上保留郵件副本,則在帳戶屬性中,單擊“高級”選項卡。勾選“在服務器上保留郵件副本”。

126免費郵箱的郵件服務器地址
    POP服務器地址: pop:  pop.126.com  
    SMTP服務器地址:smtp: smtp.126.com
在屬性設置窗口中,選擇“服務器”選項卡,然後在“發送郵件服務器”處,選中“我的服務器要求身份驗證”選項,並點擊右邊“設置”標籤,選中“使用與接收郵件服務器相同的設置”。

網易@yeah.net郵箱:   pop.yeah.net;         smtp.yeah.net
網易@netease.com郵箱:pop.netease.com;      smtp.netease.com
188.com               pop3.188.com          smtp.188.com

sina免費郵箱的郵件服務器地址爲:
    接收郵件服務器地址(POP3):pop.sina.com.cn 或:pop3.sina.com.cn
    發送郵件服務器地址(SMTP):smtp.sina.com.cn
注:在帳號的屬性中,點擊“服務器”選擇卡,單擊選中“我的服務器要求身份驗證”選項,此選擇必須選擇,

sohu閃電郵郵件服務器地址
   接收服務器:pop3.sohu.com
   外發服務器:smtp.sohu.com
在屬性設置窗口中,選擇“服務器”選項卡,勾選“我的服務器需要身份驗證”。如果你希望在服務器上保留副本,需要在上圖所示窗口中,點擊《高級》選項,勾選“在服務器上保留副本”。

yahoo.com:
    POP3服務器地址:pop.mail.yahoo.com
    SMTP服務器地址:smtp.mail.yahoo.com

yahoo.com.cn:     注意:yahoo在foxmail 4.1以上的版本設置如下:( outlook 不行的)
  POP3服務器:pop.mail.yahoo.com.cn    端口995
  SMTP服務器:smtp.mail.yahoo.com.cn   端口465
選中“我的發送服務器 (SMTP) 要求驗證”旁邊的複選框,然後選擇“使用與接收郵件服務器相同的設置”;單擊“高級”標籤頁;勾選兩個“此服務器要求加密連接(SSL)”

QQ郵箱
    POP3服務器:pop.qq.com     
  SMTP服務器:smtp.qq.com    
   SMTP服務器需要身份驗證

gmail(google.com)
    POP3服務器地址:pop.gmail.com
    SMTP服務器地址:smtp.gmail.com

139郵箱客戶端接收與發送服務器地址爲:
    接收服務器地址:pop.139.com
    發送服務器地址:smtp.139.com

21cn.com:
    POP3服務器地址:pop.21cn.com
    SMTP服務器地址:smtp.21cn.com


tom.com:
    POP3服務器地址:pop.tom.com
    SMTP服務器地址:smtp.tom.com

263.net:
    POP3服務器地址:pop3.263.net
    SMTP服務器地址:smtp.263.net

x263.net:
    POP3服務器地址:pop.x263.net
    SMTP服務器地址:smtp.x263.net
 
263.net.cn:
    POP3服務器地址:pop.263.net.cn
    SMTP服務器地址:smtp.263.net.cn

elong.com:
    POP3服務器地址:pop3.elong.com
    SMTP服務器地址:smtp.elong.com

china.com:
    POP3服務器地址:pop.china.com
    SMTP服務器地址:smtp.china.com

etang.com:
    POP3服務器地址:pop.etang.com
    SMTP服務器地址:smtp.etang.com

微軟郵件系統的設定參數如下:
  接收郵件服務器 (POP3):pop3.live.com  端口: 995      要求安全連接 (SSL)
  發送郵件服務器 (SMTP):smtp.live.com  端口:587或25   要求安全連接 (SSL)
   我的服務器要求身份驗證:     選中
   使用與接收郵件服務器相同的設置:    選中


@hushmail.com和@riseup.net安全性是值得放心的。對於收費用戶,其POP和IMAP收發郵件的參數可以如下設置:
  接收郵件服務器 (IMAP):  mailserver4.hushmail.com   端口:993  要求安全連接 (SSL)
  接收郵件服務器 (POP3):  mailserver4.hushmail.com   端口:995 要求安全連接 (SSL)
  發送郵件服務器 (SMTP):  smtp.hushmail.com   端口:tls: 587或 25  ssl: port 465  要求安全連接 (SSL)
  我的服務器要求身份驗證:     選中
  使用與接收郵件服務器相同的設置:     選中



yeah.net             <p>pop.yeah.net              <s>smtp.yeah.net    yeah.net網易免費郵箱

21cn.com             <p>pop.21cn.com              <s>smtp.21cn.com      是由世紀龍信息網絡有限公司經營的中文門戶網站
51.com               <p>210.77.145.189            <s>

100m.hl.cninfo.net   <p>100m.hl.cninfo.net        <s>100m.hl.cninfo.net   黑龍江信息港提供

btamail.net.cn       <p>btamail.net.cn            <s>btamail.net.cn      北京信息港免費郵件

freemail.nx.cninfo.net<p>freemail.nx.cninfo.net   <s>freemail.nx.cninfo.net   寬帶郵箱-寧夏信息港

371.net              <p>371.net                   <s>smtp.371.net      中國網通(集團)有限公司河南省分公司寬帶應用中心商都網

online.sh.cn         <p>pop.citiz.net             <s>smtp.citiz.net     上海熱線:中國的上海 世界的上海 -- 最上海的熱線!

citiz.net            <p>pop.citiz.net             <s>smtp.citiz.net     吸鐵石郵 Citiz.net_上海熱線

foxmail.com.cn       <p>pop.foxmail.com.cn        <s>smtp.foxmail.com.cn     深圳市騰訊計算機系統有限公司

public.guangzhou.gd.cn<p>smtp.public.guangzhou.gd.cn<s>public.guangzhou.gd.cn   廣東電信數據通信局電子郵件系統

88998.com            <p>202.100.222.86            <s>202.100.222.86      88998理財網   地址:海南省海口市龍華區國貿玉沙路中房大廈29樓 瓊B2

2911.net             <p>pop.2911.net              <s>smtp.2911.net     [超級郵

ccidnet.com          <p>pop.ccident.com           <s>smtp.ccident.com     賽迪網-工業和信息化融合的網絡服務平臺

ucs.com.tw           <p>210.66.17.1               <s>         環通電子郵

tt.zj.cn             <p>pop.email.com.cn          <s>smtp.email.com.cn      天台之窗 天台門戶網站,天台人才網,天台房產網,天台商業網,天台博...

alibaba.com          <p>pop.alibaba.com           <s>smtp.alibaba.com      阿里巴巴

fugao.net            <p>pop.email.com.cn          <s>smtp.email.com.cn       爲福州高級中學校友 提供免費的 5GB 電子郵件服務

bodachina.com        <p>bodachina.com    <s>smtp.bodachina.com       Maintenance Window開發了以博大郵件列表爲代表的系列互聯網應用軟件。

cn99.com             <p>pop.cn99.com              <s>                    Google 推出的一項服務,使電子郵件更直觀、更有效且更實用。

softhome.net         <p>pop.SoftHome.net          <s>smtp.SoftHome.net 

第2節:札記


第1章:發送郵件(mail.jar)

第0節:說明

(1)maven座標

        <!-- java 郵件包 -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>

從oracle的java擴展中可以找到相應的包,可手動下載。

(2)札記



第1節:實例

(1)簡單郵件發送器(SimpleMailSender.java)

package com.mcc.core.test.mail;

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.util.Date;
import java.util.Properties;

/**
 * 簡單郵件發送器
 *
 * @author <a href="mailto:[email protected]">menergy</a>
 *         DateTime: 14-2-16  下午8:48
 */
public class SimpleMailSender {
    /**
     * 以文本格式發送郵件
     * @param mailInfo 待發送的郵件的信息
     */
    public boolean sendTextMail(MailSenderInfo mailInfo) {
        // 判斷是否需要身份認證
        MyAuthenticator authenticator = null;
        Properties pro = mailInfo.getProperties();
        if (mailInfo.isValidate()) {
            // 如果需要身份認證,則創建一個密碼驗證器
            authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
        }
        // 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session
        Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
        try {
            // 根據session創建一個郵件消息
            Message mailMessage = new MimeMessage(sendMailSession);
            // 創建郵件發送者地址
            Address from = new InternetAddress(mailInfo.getFromAddress());
            // 設置郵件消息的發送者
            mailMessage.setFrom(from);
            // 創建郵件的接收者地址,並設置到郵件消息中
            Address to = new InternetAddress(mailInfo.getToAddress());
            mailMessage.setRecipient(Message.RecipientType.TO,to);
            // 設置郵件消息的主題
            mailMessage.setSubject(mailInfo.getSubject());
            // 設置郵件消息發送的時間
            mailMessage.setSentDate(new Date());
            // 設置郵件消息的主要內容
            String mailContent = mailInfo.getContent();
            mailMessage.setText(mailContent);
            // 發送郵件
            Transport.send(mailMessage);
            return true;
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
        return false;
    }

    /**
     * 以HTML格式發送郵件
     * @param mailInfo 待發送的郵件信息
     */
    public static boolean sendHtmlMail(MailSenderInfo mailInfo){
        // 判斷是否需要身份認證
        MyAuthenticator authenticator = null;
        Properties pro = mailInfo.getProperties();
        //如果需要身份認證,則創建一個密碼驗證器
        if (mailInfo.isValidate()) {
            authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
        }
        // 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session
        Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
        try {
            // 根據session創建一個郵件消息
            Message mailMessage = new MimeMessage(sendMailSession);
            // 創建郵件發送者地址
            Address from = new InternetAddress(mailInfo.getFromAddress());
            // 設置郵件消息的發送者
            mailMessage.setFrom(from);
            // 創建郵件的接收者地址,並設置到郵件消息中
            Address to = new InternetAddress(mailInfo.getToAddress());
            // Message.RecipientType.TO屬性表示接收者的類型爲TO
            mailMessage.setRecipient(Message.RecipientType.TO,to);
            // 設置郵件消息的主題
            mailMessage.setSubject(mailInfo.getSubject());
            // 設置郵件消息發送的時間
            mailMessage.setSentDate(new Date());
            // MiniMultipart類是一個容器類,包含MimeBodyPart類型的對象
            Multipart mainPart = new MimeMultipart();
            // 創建一個包含HTML內容的MimeBodyPart
            BodyPart html = new MimeBodyPart();
            // 設置HTML內容
            html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
            mainPart.addBodyPart(html);
            // 將MiniMultipart對象設置爲郵件內容
            mailMessage.setContent(mainPart);
            // 發送郵件
            Transport.send(mailMessage);
            return true;
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
        return false;
    }
}


(2)權限實體類(MyAuthenticator.java)

package com.mcc.core.test.mail;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

/**
 * 權限實體類
 *
 * @author <a href="mailto:[email protected]">menergy</a>
 *         DateTime: 14-2-16  下午8:49
 */
public class MyAuthenticator extends Authenticator {
    String userName=null;
    String password=null;

    public MyAuthenticator(){
    }
    public MyAuthenticator(String username, String password) {
        this.userName = username;
        this.password = password;
    }
    protected PasswordAuthentication getPasswordAuthentication(){
        return new PasswordAuthentication(userName, password);
    }
}

(3)郵件信息類(MailSenderInfo.java)

package com.mcc.core.test.mail;

import java.util.Properties;

/**
 * 郵件信息類
 *
 * @author <a href="mailto:[email protected]">menergy</a>
 *         DateTime: 14-2-16  下午8:47
 */
public class MailSenderInfo {
    // 發送郵件的服務器的IP和端口
    private String mailServerHost;
    private String mailServerPort = "25";
    // 郵件發送者的地址
    private String fromAddress;
    // 郵件接收者的地址
    private String toAddress;
    // 登陸郵件發送服務器的用戶名和密碼
    private String userName;
    private String password;
    // 是否需要身份驗證
    private boolean validate = false;
    // 郵件主題
    private String subject;
    // 郵件的文本內容
    private String content;
    // 郵件附件的文件名
    private String[] attachFileNames;
    /**
     * 獲得郵件會話屬性
     */
    public Properties getProperties(){
        Properties p = new Properties();
        p.put("mail.smtp.host", this.mailServerHost);
        p.put("mail.smtp.port", this.mailServerPort);
        p.put("mail.smtp.auth", validate ? "true" : "false");
        return p;
    }
    public String getMailServerHost() {
        return mailServerHost;
    }
    public void setMailServerHost(String mailServerHost) {
        this.mailServerHost = mailServerHost;
    }
    public String getMailServerPort() {
        return mailServerPort;
    }
    public void setMailServerPort(String mailServerPort) {
        this.mailServerPort = mailServerPort;
    }
    public boolean isValidate() {
        return validate;
    }
    public void setValidate(boolean validate) {
        this.validate = validate;
    }
    public String[] getAttachFileNames() {
        return attachFileNames;
    }
    public void setAttachFileNames(String[] fileNames) {
        this.attachFileNames = fileNames;
    }
    public String getFromAddress() {
        return fromAddress;
    }
    public void setFromAddress(String fromAddress) {
        this.fromAddress = fromAddress;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getToAddress() {
        return toAddress;
    }
    public void setToAddress(String toAddress) {
        this.toAddress = toAddress;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getSubject() {
        return subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String textContent) {
        this.content = textContent;
    }
}

(4)郵件測試類(MailTest.java)

package com.mcc.core.test.mail;

/**
 * 發送簡單的郵件消息, 依賴mail.jar包 ,接受方郵箱應該開啓OP3/SMTP服務(QQ的郵件需要在“設置”-- “賬戶”中,開啓POP3和SMTP功能)
 *
 * @author <a href="mailto:[email protected]">menergy</a>
 *         DateTime: 14-2-16  下午8:54
 */
public class MailTest {
    public static void main(String args[]){
        //設置郵件
        MailSenderInfo mailInfo = new MailSenderInfo();
        mailInfo.setMailServerHost("smtp.exmail.qq.com");
        mailInfo.setMailServerPort("25");
        mailInfo.setValidate(true);
        mailInfo.setUserName("[email protected]");
        mailInfo.setPassword("******");//您的郵箱密碼
        mailInfo.setFromAddress("[email protected]");
        mailInfo.setToAddress("[email protected]");
        mailInfo.setSubject("郵件主題");
        mailInfo.setContent("郵件內容");
        //發送郵件
        SimpleMailSender sms = new SimpleMailSender();
        sms.sendTextMail(mailInfo);//發送文體格式
        sms.sendHtmlMail(mailInfo);//發送html格式
    }
}


第2章:發送郵件(mail.jar + commons-email.jar)

第0節:說明

(1)maven座標:

        <!-- java 郵件包 -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>

        <!-- Apache 郵件協議客戶端 ,需要mail.jar包支持-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-email</artifactId>
            <version>1.3.2</version>
        </dependency>

(2)commons-email.jar包簡介

官網:http://commons.apache.org/proper/commons-email/

文檔:http://commons.apache.org/proper/commons-email/userguide.html

開源中國:http://www.oschina.net/p/commons-email/

(3)札記



第1節:實例

郵件發送處理器(EmailClientHandler.java):


package com.mcc.core.net;

import org.apache.commons.mail.*;

import java.net.URL;

/**
 * 郵件發送處理器
 * SSL on port 465
 * SMTP on port 25
 *
 * @author <a href="mailto:[email protected]">menergy</a>
 *         DateTime: 14-2-20  下午3:25
 */
public class EmailClientHandler {

    // 服務器名
    private String emailServer = null;
    // 端口
    private int emailPort = -1;
    // 用戶名
    private String emailUser = null;
    // 密碼
    private String emailPassword = null;
    //
    private MultiPartEmail multiPartEmail = null;
    //Html郵件
    private HtmlEmail htmlEmail = null;

    /**
     *  構造器
     */
    public EmailClientHandler(String emailServer, String emailUser, String emailPassword) {
        this.emailServer = emailServer;
        this.emailUser = emailUser;
        this.emailPassword = emailPassword;
    }

    /**
     *  構造器
     */
    public EmailClientHandler(String emailServer, int emailPort, String emailUser, String emailPassword) {
        this.emailServer = emailServer;
        this.emailPort = emailPort;
        this.emailUser = emailUser;
        this.emailPassword = emailPassword;
    }

    /**
     * 打開連接
     * @return
     */
    public synchronized EmailClientHandler open(){
        if(multiPartEmail == null){
            multiPartEmail = new MultiPartEmail();
        }
        return this;
    }

    /**
     * 打開連接
     * @return
     */
    public synchronized EmailClientHandler openHtml(){
        if(htmlEmail == null){
            htmlEmail = new HtmlEmail();
        }
        return this;
    }

    /**
     *獲取對象
     * @return
     */
    public  MultiPartEmail getMultiPartEmail(){
        if(multiPartEmail == null){
            multiPartEmail = new MultiPartEmail();
        }
        return multiPartEmail;
    }

    /**
     *獲取對象
     * @return
     */
    public  HtmlEmail getHtmlEmail(){
        if(htmlEmail == null){
            htmlEmail = new HtmlEmail();
        }
        return htmlEmail;
    }


    /**
     * 發送郵件
     * @param toUser
     * @param subject
     * @param msg
     * @return
     * @throws EmailException
     */
    public EmailClientHandler setSSLEmailMessage(String toUser, String subject, String msg) throws EmailException{
        //發送SSL郵件
        int sslPort = 465;
        if(emailPort != -1){
            sslPort = emailPort;
        }
        multiPartEmail.setHostName(emailServer);
        multiPartEmail.setSmtpPort(sslPort);
        multiPartEmail.setAuthenticator(new DefaultAuthenticator(emailUser, emailPassword));
        multiPartEmail.setSSLOnConnect(true);
        multiPartEmail.setFrom(emailUser);
        multiPartEmail.setSubject(subject);
        multiPartEmail.setMsg(msg);
        multiPartEmail.addTo(toUser);
        return this;
    }

    /**
     * 發送郵件
     * @param toUser
     * @param subject
     * @param msg
     * @return
     * @throws EmailException
     */
    public EmailClientHandler setSMTPEmailMessage(String toUser, String subject, String msg) throws EmailException{
        //發送SMTP郵件
        int smtpPort = 25;
        if(emailPort != -1){
            smtpPort = emailPort;
        }
        multiPartEmail.setHostName(emailServer);
        multiPartEmail.setSmtpPort(smtpPort);
        multiPartEmail.setAuthenticator(new DefaultAuthenticator(emailUser, emailPassword));
        multiPartEmail.setSSLOnConnect(true);
        multiPartEmail.setFrom(emailUser);
        multiPartEmail.setSubject(subject);
        multiPartEmail.setMsg(msg);
        multiPartEmail.addTo(toUser);
        return this;
    }

    /**
     * 發送HTML格式郵件
     * @param toUser
     * @param subject
     * @param htmlMsg
     * @param textMsg
     * @return
     * @throws EmailException
     */
    public EmailClientHandler setHTMLSSLEmailMessage(String toUser, String subject, String htmlMsg, String textMsg) throws EmailException{
        //發送SSL郵件
        int sslPort = 465;
        if(emailPort != -1){
            sslPort = emailPort;
        }
        htmlEmail.setHostName(emailServer);
        htmlEmail.setSmtpPort(sslPort);
        htmlEmail.setAuthenticator(new DefaultAuthenticator(emailUser, emailPassword));
        htmlEmail.setSSLOnConnect(true);
        htmlEmail.setFrom(emailUser);
        htmlEmail.setSubject(subject);
        htmlEmail.setHtmlMsg(htmlMsg);
        htmlEmail.setTextMsg(textMsg);
        htmlEmail.addTo(toUser);
        return this;
    }

    /**
     * 發送郵件
     * @param toUser
     * @param subject
     * @param htmlMsg
     * @param textMsg
     * @return
     * @throws EmailException
     */
    public EmailClientHandler setHTMLSMTPEmailMessage(String toUser, String subject, String htmlMsg, String textMsg) throws EmailException{
        //發送SMTP郵件
        int smtpPort = 25;
        if(emailPort != -1){
            smtpPort = emailPort;
        }
        htmlEmail.setHostName(emailServer);
        htmlEmail.setSmtpPort(smtpPort);
        htmlEmail.setAuthenticator(new DefaultAuthenticator(emailUser, emailPassword));
        htmlEmail.setSSLOnConnect(true);
        htmlEmail.setFrom(emailUser);
        htmlEmail.setSubject(subject);
        htmlEmail.setHtmlMsg(htmlMsg);
        htmlEmail.setTextMsg(textMsg);
        htmlEmail.addTo(toUser);
        return this;
    }

    /**
     * 增加附件,重複調用可增加多個
     * @param filePath 路徑加文件
     * @param attachmentName 帶後綴
     * @param description
     * @return
     * @throws EmailException
     */
    public EmailClientHandler addEmailAttachment(String filePath,String attachmentName,String description)throws EmailException{
        // 創建附件
        EmailAttachment attachment = new EmailAttachment();
        //路徑模式
        attachment.setPath(filePath);
        attachment.setDisposition(EmailAttachment.ATTACHMENT);
        attachment.setDescription(description);
        attachment.setName(attachmentName);
        multiPartEmail.attach(attachment);
        return this;
    }

    /**
     * 增加附件,重複調用可增加多個
     * @param url 附件URL
     * @param attachmentName 帶後綴
     * @param description
     * @return
     * @throws EmailException
     */
    public EmailClientHandler addEmailAttachment(URL url,String attachmentName,String description)throws EmailException{
        // 創建附件
        EmailAttachment attachment = new EmailAttachment();
        //URL模式
        attachment.setURL(url);
        attachment.setDisposition(EmailAttachment.ATTACHMENT);
        attachment.setDescription(description);
        attachment.setName(attachmentName);
        multiPartEmail.attach(attachment);
        return this;
    }

    /**
     * 增加附件,重複調用可增加多個
     * @param filePath 路徑加文件
     * @param attachmentName 帶後綴
     * @param description
     * @return
     * @throws EmailException
     */
    public EmailClientHandler addHtmlEmailAttachment(String filePath,String attachmentName,String description)throws EmailException{
        // 創建附件
        EmailAttachment attachment = new EmailAttachment();
        //路徑模式
        attachment.setPath(filePath);
        attachment.setDisposition(EmailAttachment.ATTACHMENT);
        attachment.setDescription(description);
        attachment.setName(attachmentName);
        htmlEmail.attach(attachment);
        return this;
    }

    /**
     * 增加附件,重複調用可增加多個
     * @param url 附件URL
     * @param attachmentName 帶後綴
     * @param description
     * @return
     * @throws EmailException
     */
    public EmailClientHandler addHtmlEmailAttachment(URL url,String attachmentName,String description)throws EmailException{
        // 創建附件
        EmailAttachment attachment = new EmailAttachment();
        //URL模式
        attachment.setURL(url);
        attachment.setDisposition(EmailAttachment.ATTACHMENT);
        attachment.setDescription(description);
        attachment.setName(attachmentName);
        htmlEmail.attach(attachment);
        return this;
    }

    /**
     * 發送ssl郵件
     * @return
     * @throws EmailException
     */
    public String send() throws EmailException{
        return multiPartEmail.send();
    }

    /**
     * 發送smtp郵件
     * @return
     * @throws EmailException
     */
    public String sendHtml() throws EmailException{
        return htmlEmail.send();
    }



   public static void main(String args[]){

       try {

           //發送普通文件,SSL服務器連接方式,不帶帶附件
           EmailClientHandler emailClientHandler0 = new EmailClientHandler("smtp.etonetech.com","[email protected]", "******");
           emailClientHandler0.open().setSSLEmailMessage("[email protected]", "Test subject", "Test msg").send();

//           //發送普通文件,SSL服務器連接方式,帶附件
//           EmailClientHandler emailClientHandler1 = new EmailClientHandler("smtp.etonetech.com","[email protected]", "******");
//           try {
//               emailClientHandler1.open().setSSLEmailMessage("[email protected]", "Test subject", "Test msg")
//                       .addEmailAttachment("E://data/test.jpg", "test.jpg", "")
//                       .addEmailAttachment(new URL("http://www.apache.org/images/asf_logo_wide.gif"), "test.jpg", "")
//                       .send();
//           } catch (MalformedURLException e) {
//               e.printStackTrace();
//           }

//           //發送普通文件,SMTP服務器連接方式,帶附件
//           EmailClientHandler emailClientHandler2 = new EmailClientHandler("smtp.etonetech.com","[email protected]", "******");
//           try {
//               emailClientHandler2.open().setSMTPEmailMessage("[email protected]", "Test subject", "Test msg")
//                       .addEmailAttachment("E://data/test.jpg", "test.jpg", "")
//                       .addEmailAttachment(new URL("http://www.apache.org/images/asf_logo_wide.gif"), "test.jpg", "")
//                       .send();
//           } catch (MalformedURLException e) {
//               e.printStackTrace();
//           }


//           //發送HTML文件,SMTP服務器連接方式,帶附件
//           EmailClientHandler emailClientHandler3 = new EmailClientHandler("smtp.etonetech.com","[email protected]", "******");
//           try {
//               emailClientHandler3.openHtml();
//
//               String cid = emailClientHandler3.getHtmlEmail().embed(new URL("http://www.apache.org/images/asf_logo_wide.gif"),"Apache logo");
//               String html = "<html>The apache logo - <img src=\"cid:"+cid+"\"></html>";
//               emailClientHandler3.setHTMLSMTPEmailMessage("[email protected]", "Test subject", html,"test")
//                       .addHtmlEmailAttachment("E://data/test.jpg", "test.jpg", "")
//                       .addHtmlEmailAttachment(new URL("http://www.apache.org/images/asf_logo_wide.gif"), "test.jpg", "")
//                       .sendHtml();
//           } catch (MalformedURLException e) {
//               e.printStackTrace();
//           }

//           //發送HTML文件,SMTP服務器連接方式,帶附件
//           EmailClientHandler emailClientHandler4 = new EmailClientHandler("smtp.qq.com","[email protected]", "******");
//           try {
//               emailClientHandler4.openHtml();
//
//               String cid = emailClientHandler3.getHtmlEmail().embed(new URL("http://www.apache.org/images/asf_logo_wide.gif"),"Apache logo");
//               String html = "<html>The apache logo - <img src=\"cid:"+cid+"\"></html>";
//               emailClientHandler3.setHTMLSSLEmailMessage("[email protected]", "Test subject", html,"test")
//                       .addHtmlEmailAttachment("E://data/test.jpg", "test.jpg", "")
//                       .addHtmlEmailAttachment(new URL("http://www.apache.org/images/asf_logo_wide.gif"), "test.jpg", "")
//                       .sendHtml();
//           } catch (MalformedURLException e) {
//               e.printStackTrace();
//           }


       } catch (EmailException e) {
           e.printStackTrace();
       }


   }
}




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