邮箱组件开发(使用javamail开发)

来源:互联网 发布:linux安装压缩软件 编辑:程序博客网 时间:2024/04/29 20:23
package Email;

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

import javax.activation.DataHandler;

import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Multipart;
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 sun.misc.BASE64Encoder;

/**
 * 邮件发送工具类
 */
public class EmailUtil {
    /**
     * @param to
     *            :收件人邮箱,多个之间用分号分开
     * @param subject
     *            :邮件主题
     * @param content
     *            :邮件内容
     * @param affix
     *            :附件地址,多个附件用分号";"分隔
     * @throws Exception
     */
    private Message message;
    private Properties prop;
    private String affix = ""; // 附件地址
//    private String affixName = ""; // 附件名称
    // 向multipart对象中添加邮件的附件,添加邮件内容
    private Multipart multipart = new MimeMultipart();

    public void sendWithAttach(String to, String subject, String content,
            String affix) throws Exception {
        methodFirst(to, subject);
        setAffix(affix);
        addContent(content);
        addAttachment();
        sendLast();
        System.out.println("发送成功");
    }

    /**
     *
     * @param to
     *            :收件人邮箱,多个之间用分号分开
     * @param cc
     *            :抄送人邮箱,多个之间用分号分开
     * @param title
     *            :邮件主题
     * @param content
     *            :邮件内容
     * @param affix
     *            :附件地址,多个附件用分号";"分隔
     *
     * @throws Exception
     */
    public void sendWithAttach(String to, String cc, String subject, String content,
            String affix) throws Exception {
        methodFirst(to, subject);
        setAffix(affix);
        addContent(content);
        methodCc(cc);
        addAttachment();
        sendLast();

        System.out.println("发送成功");
    }

    /**
     *
     * @param to
     *            :收件人邮箱,多个之间用分号分开
     * @param cc
     *            :抄送人邮箱,多个之间用分号分开
     * @param bcc
     *            :暗送人邮箱,多个之间用分号分开
     * @param title
     *            :邮件主题
     * @param content
     *            :邮件内容
     * @param affix
     *            :附件地址,多个附件用分号";"分隔
     *
     * @throws Exception
     */
    public void sendWithAttach(String to, String cc, String bcc, String subject,
            String content, String affix) throws Exception {
        methodFirst(to, subject);
        setAffix(affix);
        addContent(content);
        methodCc(cc);
        methodBcc(bcc);
        addAttachment();
        sendLast();
        System.out.println("发送成功");
    }

    /***********************************************************************/
    /**
     * @param to
     *            :收件人邮箱,多个之间用分号分开
     * @param subject
     *            :邮件主题
     * @param content
     *            :邮件内容
     * @throws Exception
     */
    public void send(String to, String subject, String content)
            throws Exception {
        methodFirst(to, subject);
        addContent(content);
        sendLast();
        System.out.println("发送成功");
    }

    /**
     *
     * @param to
     *            :收件人邮箱,多个之间用分号分开
     * @param cc
     *            :抄送人邮箱,多个之间用分号分开
     * @param title
     *            :邮件主题
     * @param content
     *            :邮件内容
     *
     * @throws Exception
     */
    public void send(String to, String cc, String subject, String content)
            throws Exception {
        methodFirst(to, subject);
        methodCc(cc);
        addContent(content);
        sendLast();
        System.out.println("发送成功");
    }

    /**
     *
     * @param to
     *            :收件人邮箱,多个之间用分号分开
     * @param cc
     *            :抄送人邮箱,多个之间用分号分开
     * @param bcc
     *            :暗送人邮箱,多个之间用分号分开
     * @param title
     *            :邮件主题
     * @param content
     *            :邮件内容
     *
     * @throws Exception
     */
    public void send(String to, String cc, String bcc, String subject,
            String content) throws Exception {
        if(to!=null&&!to.equals("")&&(cc.equals("") || cc==null)&&(bcc.equals("") || bcc==null)){
            send(to, subject, content);
        }else if(to!=null&&!to.equals("")&&cc!=null&&!cc.equals("")&&(bcc.equals("") || bcc==null)){
            send(to, cc, subject, content);
        }else if(to!=null&&!to.equals("")&&cc!=null&&!cc.equals("")&&!bcc.equals("")&&bcc!=null){
        methodFirst(to, subject);
        methodCc(cc);
        methodBcc(bcc);
        addContent(content);
        sendLast();
        System.out.println("发送成功");
        }
        else{
            throw new Exception("参数异常,请仔细检查参数");
        }
    }

    /**
     * @return Properties 读取properties文件的值,Properties放在src路径下
     * @throws Exception
     */
    public static Properties getProp() {
        InputStream in = EmailUtil.class.getClassLoader().getResourceAsStream(
                "email.properties");
        Properties prop = new Properties();
        try {
            prop.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return prop;
    }

    /**
     * 发送流程:设置收件人,主题
     *
     * @throws Exception
     */
    public void methodFirst(String to, String subject) throws Exception {
        prop = getProp();
        // 设置基本参数
        Properties props = new Properties();
        // 设置主机
        props.setProperty("mail.host", prop.getProperty("UrlHost"));
        // 确定使用权限验证
        props.setProperty("mail.smtp.auth", "true");
        // 确定账号与密码
        Authenticator authenticator = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(prop.getProperty("user"),
                        prop.getProperty("password"));
            }
        };

        // 获得连接
        Session session = Session.getDefaultInstance(props, authenticator);

        // 编写消息
        message = new MimeMessage(session);
        // 发件人
        message.setFrom(new InternetAddress(prop.getProperty("from")));
        // 收件人 , to:收件人 cc:抄送 bcc:暗送
        String[] tos = to.split(";");
        InternetAddress[] ia = new InternetAddress[tos.length];
        for (int i = 0; i < tos.length; i++) {
            ia[i] = new InternetAddress(tos[i]);
        }
        message.setRecipients(RecipientType.TO, ia);
        // 邮件 主题
        message.setSubject(subject);
    }

    /**
     * @param content
     * @throws MessagingException
     *             发送流程:添加邮件内容
     */
    public void addContent(String content) throws MessagingException {
        // 设置邮件的文本内容
        BodyPart contentPart = new MimeBodyPart();
        contentPart.setText(content);
        multipart.addBodyPart(contentPart);
    }

    /**
     * 邮件抄送方法
     */
    public void methodCc(String cc) {
        String[] ccs = cc.split(";");
        InternetAddress[] iacc = new InternetAddress[ccs.length];
        for (int i = 0; i < ccs.length; i++) {
            try {
                iacc[i] = new InternetAddress(ccs[i]);
            } catch (AddressException e) {

                e.printStackTrace();
            }
        }
        try {
            message.setRecipients(RecipientType.CC, iacc);
        } catch (MessagingException e) {

            e.printStackTrace();
        }
    }

    /**
     * 邮件密送方法
     */
    public void methodBcc(String bcc) {
        String[] bccs = bcc.split(";");
        InternetAddress[] iabcc = new InternetAddress[bccs.length];
        for (int i = 0; i < bccs.length; i++) {
            try {
                iabcc[i] = new InternetAddress(bccs[i]);
            } catch (AddressException e) {

                e.printStackTrace();
            }
        }
        try {
            message.setRecipients(RecipientType.BCC, iabcc);
        } catch (MessagingException e) {
            
            e.printStackTrace();
        }
    }

    /**
     * 设置附件参数值
     * @param affix附件地址
     *
     */
    public void setAffix(String affix) {
        this.affix = affix;
//        this.affixName = affixName;
    }

    /**
     * 发送邮件流程:添加附件
     */
    public void addAttachment() {
        String[] strs=affix.split(";");
        if(strs!=null){
            MimeBodyPart mbp;
            FileDataSource source;
            // 逐个加入附件  
            for (int j = 0; j < strs.length; j++) {  
                mbp = new MimeBodyPart();  
                source = new FileDataSource(strs[j]);  
                try {  
                    mbp.setDataHandler(new DataHandler(source));  
                    BASE64Encoder enc = new BASE64Encoder();
                    mbp.setFileName("=?GBK?B?"+enc.encode(source.getName().getBytes())+ "?=");  
                    multipart.addBodyPart(mbp);  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
        }

    }

    /**
     * 发送邮件流程:添加邮件内容,发送
     */
    public void sendLast() {
        // 发送消息
        try {
            message.setContent(multipart,
                    "text/html;charset=" + prop.getProperty("code"));
            message.saveChanges();
            Transport.send(message);
        } catch (Exception e) {

            e.printStackTrace();
        }
    }
}

配置文件email.properties,放在了src下

内容如下:

#以下为邮箱发送类配置信息
#邮箱主机地址
UrlHost=smtp.qq.com
#邮箱用户名
user=728975282@qq.com
#密码
password=1234
#邮件内容编码字符集
code=utf-8
#发件人(有的发件人可以与邮箱用户名相同,有的不同,这取决于底层是否对两者一致性的验证,
#一般而言,两者应该是一致的)
from=728975282@qq.com

0 0
原创粉丝点击