Java邮件发送详解(可发送附件)

发送前需要引用mail-1.4.5.jar,资源下载参见下载链接。

一、邮件内容实体类

package mail;

import java.security.GeneralSecurityException;
import java.util.Properties;

import com.sun.mail.util.MailSSLSocketFactory;

public class MailInfo {
    /** 发送邮件的服务器的IP */
    private String mailHost;
    /** 发送邮件的服务器的端口 */
    private String mailPort = "465";
    /** 发送邮件的用户名(邮箱全名称) */
    private String username;
    /** 发送邮件的密码 */
    private String password;

    /** 错误信息发送地址(多个邮件地址以";"分隔) */
    private String errorTo;
    /** 错误信息抄送地址(多个邮件地址以";"分隔) */
    private String errorCc;
    /** 警告信息发送地址(多个邮件地址以";"分隔) */
    private String warningTo;
    /** 警告信息抄送地址(多个邮件地址以";"分隔) */
    private String warningCc;
    /** 通知信息发送地址(多个邮件地址以";"分隔) */
    private String notifyTo;
    /** 通知信息抄送地址(多个邮件地址以";"分隔) */
    private String notifyCc;

    /** 邮件主题 */
    private String subject;
    /** 邮件内容 */
    private String content;
    /** 邮件附件的文件名 */
    private String[] attachFileNames;

    /**
     * 获取邮件参数
     * 
     * @return
     * @throws GeneralSecurityException
     */
    public Properties getProperties() throws GeneralSecurityException {
        Properties props = new Properties();
        props.put("mail.smtp.host", getMailHost());
        props.put("mail.smtp.port", getMailPort());
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");

        MailSSLSocketFactory sslSF = new MailSSLSocketFactory();
        sslSF.setTrustAllHosts(true);
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sslSF);
        props.put("mail.transport.protocol", "smtp");

        props.put("mail.user", getUsername());
        props.put("mail.password", getPassword());
        return props;
    }

    /**
     * @return the mailHost
     */
    public String getMailHost() {
        return mailHost;
    }

    /**
     * @param mailHost
     *            
     */
    public void setMailHost(String mailHost) {
        this.mailHost = mailHost;
    }

    /**
     * @return the mailPort
     */
    public String getMailPort() {
        return mailPort;
    }

    /**
     * @param mailPort
     *            
     */
    public void setMailPort(String mailPort) {
        this.mailPort = mailPort;
    }

    /**
     * @return the username
     */
    public String getUsername() {
        return username;
    }

    /**
     * @param username
     *            
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * @param password
     * 
     */
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * @return the errorTo
     */
    public String getErrorTo() {
        return errorTo;
    }

    /**
     * @param errorTo
     *            
     */
    public void setErrorTo(String errorTo) {
        this.errorTo = errorTo;
    }

    /**
     * @return the errorCc
     */
    public String getErrorCc() {
        return errorCc;
    }

    /**
     * @param errorCc
     *            
     */
    public void setErrorCc(String errorCc) {
        this.errorCc = errorCc;
    }

    /**
     * @return the warningTo
     */
    public String getWarningTo() {
        return warningTo;
    }

    /**
     * @param warningTo
     *            
     */
    public void setWarningTo(String warningTo) {
        this.warningTo = warningTo;
    }

    /**
     * @return the warningCc
     */
    public String getWarningCc() {
        return warningCc;
    }

    /**
     * @param warningCc
     *            
     */
    public void setWarningCc(String warningCc) {
        this.warningCc = warningCc;
    }

    /**
     * @return the notifyTo
     */
    public String getNotifyTo() {
        return notifyTo;
    }

    /**
     * @param notifyTo
     *            
     */
    public void setNotifyTo(String notifyTo) {
        this.notifyTo = notifyTo;
    }

    /**
     * @return the notifyCc
     */
    public String getNotifyCc() {
        return notifyCc;
    }

    /**
     * @param notifyCc
     *            
     */
    public void setNotifyCc(String notifyCc) {
        this.notifyCc = notifyCc;
    }

    /**
     * @return Returns the subject.
     */
    public String getSubject() {
        return subject;
    }

    /**
     * @param subject
     *            
     */
    public void setSubject(String subject) {
        this.subject = subject;
    }

    /**
     * @return Returns the content.
     */
    public String getContent() {
        return content;
    }

    /**
     * @param content
     *            
     */
    public void setContent(String content) {
        this.content = content;
    }

    /**
     * @return Returns the attachFileNames.
     */
    public String[] getAttachFileNames() {
        return attachFileNames;
    }

    /**
     * @param attachFileNames
     *            
     */
    public void setAttachFileNames(String[] attachFileNames) {
        this.attachFileNames = attachFileNames;
    }
}

二、发送邮件时的身份验证器

package mail;

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

public class MailAuthenticator extends Authenticator {
    /** 用户账号 */
    private String userName = null;
    /** 用户口令 */
    private String password = null;

    /**
     * @param userName
     * @param password
     */
    public MailAuthenticator(String userName, String password) {
        this.userName = userName;
        this.password = password;
    }

    /**
     * 身份验证
     * @return
     */
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(userName, password);
    }

}

三、邮件发送器

package mail;

import java.util.Calendar;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class MailSender {

    private static MailSender sender = null;


    public static MailSender getInstance() {
        if(sender == null){
            sender = new MailSender();
        }
        return sender;
    }

    /**
     * 以文本格式发送邮件
     * 
     * @param mailInfo
     *            邮件信息
     * @param mailType
     *            邮件类型 1-error;2-warning;3-notify;
     * @return
     * @throws Exception
     */
    public boolean sendTextMail(MailInfo mailInfo, int mailType) throws Exception {

        // 需要身份认证,创建一个密码验证器
        MailAuthenticator authenticator = new MailAuthenticator(mailInfo.getUsername(), mailInfo.getPassword());

        Properties prop = mailInfo.getProperties();
        // 根据邮件会话属性和密码验证器构造一个发送邮件的session
        Session sendMailSession = Session.getDefaultInstance(prop, authenticator);

        try {
            // 根据session创建一个邮件消息
            Message mailMessage = new MimeMessage(sendMailSession);
            // 创建邮件发送者地址
            Address from = new InternetAddress(mailInfo.getUsername());
            // 设置邮件消息的发送者
            mailMessage.setFrom(from);

            // 创建邮件的接收者地址 to:发送;cc:抄送
            Address[][] maillToArr = getMailToAddress(mailInfo, mailType);

            // 设置邮件消息的接收者,发送,抄送
            if (maillToArr != null && maillToArr[0] != null && maillToArr[0].length > 0) {
                mailMessage.setRecipients(Message.RecipientType.TO, maillToArr[0]);
            }
            if (maillToArr != null && maillToArr[1] != null && maillToArr[1].length > 0) {
                mailMessage.setRecipients(Message.RecipientType.CC, maillToArr[1]);
            }

            // 设置邮件消息的主题
            mailMessage.setSubject(mailInfo.getSubject());
            // 设置邮件消息发送的时间
            mailMessage.setSentDate(Calendar.getInstance().getTime());
            // 设置邮件消息的主要内容
            mailMessage.setText(mailInfo.getContent());

            // 发送邮件
            Transport.send(mailMessage);

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    /**
     * 以HTML格式发送邮件
     * 
     * @param mailInfo
     *            邮件信息
     * @param mailType
     *            邮件类型 1-error;2-warning;(默认)3-notify;
     * @return
     * @throws Exception
     */
    public boolean sendHtmlMail(MailInfo mailInfo, int mailType) throws Exception {

        // 需要身份认证,创建一个密码验证器
        MailAuthenticator authenticator = new MailAuthenticator(mailInfo.getUsername(), mailInfo.getPassword());

        Properties prop = mailInfo.getProperties();
        // 根据邮件会话属性和密码验证器构造一个发送邮件的session
        Session sendMailSession = Session.getDefaultInstance(prop, authenticator);

        try {
            // 根据session创建一个邮件消息
            Message mailMessage = new MimeMessage(sendMailSession);
            // 创建邮件发送者地址
            Address from = new InternetAddress(mailInfo.getUsername());
            // 设置邮件消息的发送者
            mailMessage.setFrom(from);

            // 创建邮件的接收者地址 to:发送;cc:抄送
            Address[][] maillToArr = getMailToAddress(mailInfo, mailType);

            // 设置邮件消息的接收者,发送,抄送
            if (maillToArr != null && maillToArr[0] != null && maillToArr[0].length > 0) {
                mailMessage.setRecipients(Message.RecipientType.TO, maillToArr[0]);
            }
            if (maillToArr != null && maillToArr[1] != null && maillToArr[1].length > 0) {
                mailMessage.setRecipients(Message.RecipientType.CC, maillToArr[1]);
            }

            // 设置邮件消息的主题
            mailMessage.setSubject(mailInfo.getSubject());
            // 设置邮件消息发送的时间
            mailMessage.setSentDate(Calendar.getInstance().getTime());

            // MimeMultipart类是一个容器类,包含MimeBodyPart类型的对象
            Multipart multiPart = new MimeMultipart();
            // 创建一个包含HTML内容的MimeBodyPart
            BodyPart bodyPart = new MimeBodyPart();
            // 设置html邮件消息内容
            bodyPart.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
            multiPart.addBodyPart(bodyPart);

            //添加附件
            if(mailInfo.getAttachFileNames().length != 0){
                for(String attachFile : mailInfo.getAttachFileNames()){
                    bodyPart=new MimeBodyPart();  
                    FileDataSource fds=new FileDataSource(attachFile); //得到数据源  
                    bodyPart.setDataHandler(new DataHandler(fds)); //得到附件本身并放入BodyPart  
                    bodyPart.setFileName(MimeUtility.encodeText(fds.getName()));  //得到文件名并编码(防止中文文件名乱码)同样放入BodyPart  
                    multiPart.addBodyPart(bodyPart);  
                }
            }

            // 设置邮件消息的主要内容
            mailMessage.setContent(multiPart);

            // 发送邮件
            Transport.send(mailMessage);

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    /**
     * 创建发送邮件列表地址对象
     * 
     * @param mailInfo
     *            邮件信息
     * @param mailType
     *            邮件类型 1-error;2-warning;(默认)3-notify;
     * @return Address[0]:发送地址数组;Address[1]:抄送地址数组
     */
    private Address[][] getMailToAddress(MailInfo mailInfo, int mailType) throws AddressException {
        Address[] toAdds = null;
        Address[] ccAdds = null;

        String[] toMails = mailInfo.getNotifyTo().split(";");
        toAdds = new InternetAddress[toMails.length];
        for (int index = 0; index < toMails.length; index++) {
            toAdds[index] = new InternetAddress(toMails[index]);
        }
        String[] ccMails = mailInfo.getNotifyCc().split(";");
        ccAdds = new InternetAddress[ccMails.length];
        for (int index = 0; index < ccMails.length; index++) {
            ccAdds[index] = new InternetAddress(ccMails[index]);
        }

        Address[][] result = { toAdds, ccAdds };
        return result;
    }

    /**
     * 构建MailInfo对象
     * @return
     */
    public MailInfo getMailInfo() {
        MailInfo info = new MailInfo();
        info.setMailHost("邮件提供商的stmp服务器");
        info.setMailPort("465");
        info.setUsername("邮件发送人邮箱");
        info.setPassword("发送人邮箱密码");
        info.setNotifyTo("邮件接收人");
        info.setNotifyCc("邮件抄送人");
        info.setSubject("java send mail test");
        info.setContent("中文编码测试,看是不是乱码");
        info.setAttachFileNames(new String[]{"附件一", "附件二"});//添加附件
        return info;
    }
}

四、测试程序

package mail;

public class MailTest {

    public static void main(String[] args) throws Exception {
        MailSender mailSender = MailSender.getInstance();
        MailInfo mailInfo = mailSender.getMailInfo();
        mailSender.sendHtmlMail(mailInfo, 3);
    }
}

你可能感兴趣的:(Language,J2EE,Java)