Java发送电子邮件

package com.mbit.common.util;


import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
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.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

/**
 * 发送邮件工具类
 * @author guannengjie
 *
 */
public class SendEmailUtil {

    /**
     * 发送的邮箱 默认地址
     */
    private static final String USER = "***@qq.com";
    /**
     * 授权密码 【授权密码不是邮箱密码,邮箱授权密码要自己去申请,具体百度!】
     */
    private static final String PWD = "hdwhkcsgkpcdbjca";

    /**
     * 发送邮件简化版
     * @param to   收件人邮箱地址
     * @param subject 主题
     * @param content 内容
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    public static void sendMessage(String[] to,String subject,String content) throws MessagingException, UnsupportedEncodingException {
        sendMessage(USER,PWD,to,null,null,null,subject,content);
    }


    /**
     * 发送邮件 支持任意邮箱
     * @param user 发件人邮箱地址
     * @param pwd  发件人邮箱授权码
     * @param to   收件人邮箱地址
     * @param cc   抄送人邮箱地址
     * @param bcc  密送人邮箱地址
     * @param fileList 附件(路径)
     * @param subject 主题
     * @param content 内容
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    public static void sendMessage(String user,String pwd,String[] to,String[] cc,String[] bcc,String[] fileList,String subject,String content) throws MessagingException, UnsupportedEncodingException {
        // 配置发送邮件的环境属性
        final Properties props = new Properties();
        //下面两段代码是设置ssl和端口,不设置发送不出去。
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.socketFactory.port", "465");
        // 设置传输协议
        props.setProperty("mail.transport.protocol", "smtp");
        //是否需要认证
        props.put("mail.smtp.auth", "true");
        // QQ邮箱的服务器 如果是企业邮箱或者其他邮箱得更换该服务器地址
        props.put("mail.smtp.host", "smtp.qq.com");
        // 发件人的账号
        props.put("mail.user", user);
        // 访问SMTP服务时需要提供的密码
        props.put("mail.password", pwd);
        // 构建授权信息,用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        //  使用环境属性和授权信息,创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        //  创建邮件消息
        MimeMessage message = new MimeMessage(mailSession);
        BodyPart messageBodyPart = new MimeBodyPart();
        Multipart multipart = new MimeMultipart();
        //  设置发件人
        InternetAddress form = new InternetAddress(props.getProperty("mail.user"));
        message.setFrom(form);
        //  收件地址
        if (to != null) {
            String toList = getMailList(to);
            InternetAddress[] iaToList = InternetAddress.parse(toList);
            message.setRecipients(RecipientType.TO, iaToList);
        }
        //  抄送地址
        if (cc != null) {
            String toListcc = getMailList(cc);
            InternetAddress[] iaToListcc =  InternetAddress.parse(toListcc);
            message.setRecipients(RecipientType.CC, iaToListcc);
        }
        //  密送地址
        if (bcc != null) {
            String toListbcc = getMailList(bcc);
            InternetAddress[] iaToListbcc = InternetAddress.parse(toListbcc);
            message.setRecipients(RecipientType.BCC, iaToListbcc);
        }
        // 发送日期 该日期可以随意写
        message.setSentDate(new Date());
        // 主题
        message.setSubject(subject);
        // 内容
        message.setText(content);
        //显示以html格式的文本内容
        messageBodyPart.setContent(content,"text/html;charset=utf-8");
        multipart.addBodyPart(messageBodyPart);
        //保存多个附件
        if(fileList!=null){
            addTach(fileList, multipart);
        }
        message.setContent(multipart);
        // 发送邮件
        Transport.send(message);
    }

    /**
     * 将多个邮箱地址的数组格式化输出为字符串
     * @param mailArray
     * @return
     */
    private static String getMailList(String[] mailArray) {
        StringBuffer toList = new StringBuffer();
        int length = mailArray.length;
        if (mailArray != null && length < 2) {
            toList.append(mailArray[0]);
        } else {
            for (int i = 0; i < length; i++) {
                toList.append(mailArray[i]);
                if (i != (length - 1)) {
                    toList.append(",");
                }
            }
        }
        return toList.toString();
    }

    /**
     * 添加多个附件
     * @param fileList
     * @param multipart
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    public static void addTach(String [] fileList, Multipart multipart) throws MessagingException, UnsupportedEncodingException {
        for (int index = 0; index < fileList.length; index++) {
            MimeBodyPart mailArchieve = new MimeBodyPart();
            FileDataSource fds = new FileDataSource(fileList[index]);
            mailArchieve.setDataHandler(new DataHandler(fds));
            mailArchieve.setFileName(MimeUtility.encodeText(fds.getName(),"UTF-8","B"));
            multipart.addBodyPart(mailArchieve);
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值