采用JavaMail发送邮件

1. Mail.java   邮件类,需要设置: 帐户名和密码、收件人、抄送人(可选)、暗送人(可选)、主题、内容、附件(可选)
package com.javaweb.mail;

import java.util.ArrayList;
import java.util.List;
/**
 * 邮件类,需要设置: 帐户名和密码、收件人、抄送人(可选)、暗送人(可选)、主题、内容、附件(可选)
 * 在创建了Mail对象之后
 * 可以调用它的setSubject()、setContent(),设置主题和正文
 * 也可以调用setFrom()和 addToAddress(),设置发件人,和添加收件人。
 * 也可以调用addAttch()添加附件
 * 创建AttachBean:new AttachBean(new File("..."), "fileName");
 * @author Administrator
 *
 */
public class Mail {

    private String from;    // 发件人
    private StringBuilder toAddress = new StringBuilder();//收件人
    private StringBuilder ccAddress = new StringBuilder();//抄送
    private StringBuilder bccAddress = new StringBuilder();//暗送
    private String subject;// 主题
    private String content;//正文
    // 附件列表
    private List<AttachBean> attachs = new ArrayList<AttachBean>();
    
    public Mail() {
        super();
    }
    
    public Mail(String from, String to, String subject, String content) {
        super();
        this.from = from;
        this.toAddress.append(to);
        this.subject = subject;
        this.content = content;
    }

    /**
     * 设置发送人
     * @return
     */
    public String getFrom() {
        return from;
    }
    /**
     * 返回发送人
     * @param from
     */
    public void setFrom(String from) {
        this.from = from;
    }
    /**
     * 获取收件人
     * @return
     */
    public String getToAddress() {
        return toAddress.toString();
    }
    /**
     * 添加收件人,可以添加多个收件人
     * @param toAddress
     */
    public void addToAddress(String to) {
        if(this.toAddress.length() > 0){
            this.toAddress.append(",");
        }
        this.toAddress.append(to);
    }
    /**
     * 获取暗送人
     * @return
     */
    public String getCcAddress() {
        return ccAddress.toString();
    }
    /**
     * 添加抄送人,可以添加多个抄送人
     * @param cc
     */
    public void addCcAddress(String cc) {
        if(this.ccAddress.length()>0){
            this.ccAddress.append(",");
        }
        this.ccAddress.append(cc).toString();
    }
    /**
     * 获取暗送人
     * @return
     */
    public String getBccAddress() {
        return bccAddress.toString();
    }
    /**
     * 添加暗送人,可以添加多个暗送人
     * @param bccAddress
     */
    public void addBccAddress(String bcc) {
        if(this.bccAddress.length()>0){
            this.bccAddress.append(",");
        }
        this.bccAddress.append(bcc);
    }
    /**
     * 获取主题
     * @return
     */
    public String getSubject() {
        return subject;
    }
    /**
     * 设置主题
     * @param subject
     */
    public void setSubject(String subject) {
        this.subject = subject;
    }
    /**
     * 获取正文内容
     * @return
     */
    public String getContent() {
        return content;
    }
    /**
     * 设置正文内容
     * @param content
     */
    public void setContent(String content) {
        this.content = content;
    }
    /**
     * 获取所有附件
     * @return
     */
    public List<AttachBean> getAttachs() {
        return attachs;
    }
    /**
     * 添加附件,可以添加多个附件
     * @param attach
     */
    public void addAttachs(AttachBean attach) {
        this.attachs.add(attach);
    }
    
}
2. AttachBean.java 附件类
package com.javaweb.mail;

import java.io.File;
/**
 * 附件类
 * @author Administrator
 *
 */
public class AttachBean {

    private String cid;
    private File file;
    private String fileName;
    
    public String getCid() {
        return cid;
    }
    public void setCid(String cid) {
        this.cid = cid;
    }
    public File getFile() {
        return file;
    }
    public void setFile(File file) {
        this.file = file;
    }
    public String getFileName() {
        return fileName;
    }
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
    public AttachBean() {
        super();
    }
    public AttachBean(File file, String fileName) {
        super();
        this.file = file;
        this.fileName = fileName;
    }
    
    
}
3.MailUtils.java   JavaMail工具类 两方法:1. 获取 Session  createSession(String host, final String userName, final String password)              2. 发送邮件 send(Session session,final Mail mail)
package com.javaweb.mail;

import java.io.IOException;
import java.util.List;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
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 MailUtils {

    /**
     * 创建Session
     * @param host 服务器名
     * @param userName 帐户名
     * @param password 帐户密码
     * @return
     */
    public static Session createSession(String host, final String userName, final String password){
        Properties props = new Properties();
        props.setProperty("mail.host", host);// 设置主机名称
        props.setProperty("mail.smtp.auth", "true");//指定验证
        // 创建验证器
        Authenticator auth = new Authenticator(){
            public PasswordAuthentication getPasswordAuthentication(){
                return new PasswordAuthentication(userName, password);
            }
        };
        // 返回Session
        return Session.getInstance(props, auth);
    }
    /**
     * 发邮件
     * @param session
     * @param mail
     * @throws AddressException
     * @throws MessagingException
     * @throws IOException
     */
    public static void send(Session session,final Mail mail) throws AddressException, MessagingException, IOException{
        MimeMessage msg = new MimeMessage(session);
        
        msg.setFrom(new InternetAddress(mail.getFrom()));//设置发件人
        msg.setSubject(mail.getSubject());// 设置主题
        msg.addRecipients(RecipientType.TO, mail.getToAddress());//收件人
        String cc = mail.getCcAddress();
        if(cc != null){
            msg.addRecipients(RecipientType.CC, cc);// 抄送
        }
        String bcc = mail.getBccAddress();
        if(bcc != null){
            msg.addRecipients(RecipientType.BCC, bcc);// 暗送
        }
        //创建部件集对象
        MimeMultipart multipart = new MimeMultipart();
        // 创建一个部件
        MimeBodyPart bodyPart = new MimeBodyPart();
        bodyPart.setContent(mail.getContent(), "text/html;charset=utf-8");
        multipart.addBodyPart(bodyPart);//把部件设置到部件集中
        
        // 添加附件
        List<AttachBean> attachBeanList = mail.getAttachs();
        
        if(attachBeanList != null){
            for(AttachBean attach : attachBeanList){
                MimeBodyPart attachPart = new MimeBodyPart();
                attachPart.attachFile(attach.getFile());// 设置附件文件
                // 设置文件名
                attachPart.setFileName(MimeUtility.encodeText(attach.getFileName()));
                String cid = attach.getCid();
                if(cid != null){
                    attachPart.setContentID(cid);
                }
                multipart.addBodyPart(attachPart);//把部件设置到部件集中
            }
        }
        
        msg.setContent(multipart);//设置内容
        
        Transport.send(msg);// 发送邮件
    }
    
}
 

相关内容推荐