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();
       }


   }
}




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