[JAVA工具类]--邮件发送

所需依赖: javax.mail
POM依赖配置

<dependency>
      <groupId>javax.mail</groupId>
      <artifactId>mail</artifactId>
</dependency>

如果发送方为企业邮箱,Exchange,请更改HOST参数。

这个邮件发送工具类,也是从网上摘抄了好几段,具体的出处已经找不到了。

package com.kaijiyu.util;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
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;

/**
 * 邮件发送类
 * Created by kaijiyu on 2017/11/2.
 */
public class SendMailUtil {

    private static final Logger logger = LoggerFactory.getLogger(SendMailUtil.class);

    /**
     * 设置会话
     *
     * @param protocol 服务器链接方式
     * @return
     */
    public static Session getSession(String protocol) {
        Properties mailProps = new Properties();
        mailProps.put("mail.smtp.auth", "true");//向SMTP服务器提交用户认证
        mailProps.put("mail.transport.protocol", protocol);//指定发送邮件协议
        //getInstance每次都会拿一个新的session,而getDefaultInstance拿的是同一个session
        Session session = Session.getDefaultInstance(mailProps);
        // session.setDebug(true);//调试模式
        return session;
    }

    /**
     * 发送邮件
     *
     * @param file    附件
     * @param subject 标题
     * @param content 邮件内容
     * @return
     */
    public static void sendEmail(File file, String subject, String content) {
        try {
            String protocol = "smtp";
            MimeMessage message = getTextMessage(getSession(protocol), file, subject, content);
            String host = "smtp.163.com";//连接发送方的SMTP服务器,如果是企业邮箱,改为企业邮箱服务器
            String user = "userName@163.com";//用户名
            String password = "Ri!75@yjmt9ro";//密码
            //从session中取mail.smtp.protocol指定协议的Transport
            Transport transport = getSession(protocol).getTransport();
            //建立与指定的SMTP服务器的连接
            transport.connect(host, user, password);
            //发给所有指定的收件人,若使用message.getAllRecipients()则还包括抄送和暗送的人
            transport.sendMessage(message, message.getAllRecipients());
            //关闭连接
            transport.close();
        } catch (Exception e) {
            logger.error("邮件发送失败", e);
        }
    }

    /**
     * 设置邮件基本参数
     *
     * @param session 会话
     * @param subject 标题
     * @param file    附件
     * @param content 正文
     * @return
     */
    public static MimeMessage getTextMessage(Session session, File file, String subject, String content)
            throws AddressException, MessagingException, UnsupportedEncodingException {
        MimeMessage message = new MimeMessage(session);

        try {
            // 获取配置文件
            InputStream is = SendMailUtil.class.getClassLoader().getResourceAsStream("sendmail.properties");
            Properties properties = new Properties();
            BufferedReader bf = new BufferedReader(new InputStreamReader(is));
            properties.load(bf);
            String[] toList = properties.getProperty("email.to").split(";");
            String[] copyToList = properties.getProperty("email.cc").split(";");
            message.setFrom(new InternetAddress("userName@163.com"));// 设置发送人
            // 设置收件人列表
            if (toList.length > 0) {
                String toListStr = getMailList(toList);
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toListStr));
            }
            // 设置抄送人列表
            if (copyToList.length > 0) {
                String ccListStr = getMailList(copyToList);
                message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccListStr));
            }
            // 设置主题
            message.setSubject(subject);
            MimeMultipart mmp = new MimeMultipart("mixed");
            BodyPart bp = new MimeBodyPart();
            // 设置正文
            bp.setContent(content, "text/html;charset=utf-8");
            mmp.addBodyPart(bp);
            // 设置附件
            if (StringUtils.isNotBlank(file.getPath())) {
                MimeBodyPart attached2BodyPart = getAttachedBodyPart(file);
                mmp.addBodyPart(attached2BodyPart);
            }
            message.setContent(mmp);
            message.saveChanges();
        } catch (MessagingException | UnsupportedEncodingException e) {
            logger.error("邮件内容设置失败" + e);
        } catch (IOException e) {
            logger.error("配置文件读取失败" + e);
        }
        return message;
    }

    /**
     * 处理文件名 ,此处是针对Window下的。
     *
     * @param filePath
     * @return
     */
    public static String doHandlerFileName(String filePath) {
        String fileName = filePath;
        if (null != filePath && !"".equals(filePath)) {
            fileName = filePath.substring(filePath.lastIndexOf("//") + 1);
        }
        return fileName;
    }

    /**
     * 处理html加图片的类型(related)
     *
     * @param content
     * @param picName
     * @return
     * @throws MessagingException
     */
    public static MimeBodyPart getPicBodyPart(String content, String picName) throws MessagingException {
        MimeBodyPart contentPart = new MimeBodyPart();
        MimeMultipart mmp = new MimeMultipart("related");//此处MIME消息头组合类型为related
        MimeBodyPart contented = new MimeBodyPart();
        contented.setContent(content, "text/html;charset=gb2312");//因正文内容中有中文
        mmp.addBodyPart(contented);
        MimeBodyPart picBodyPart = new MimeBodyPart();
        FileDataSource fds = new FileDataSource(picName);
        picBodyPart.setDataHandler(new DataHandler(fds));
        picBodyPart.setContentID("my1.jpg");//设置contentId
        mmp.addBodyPart(picBodyPart);
        contentPart.setContent(mmp);
        return contentPart;
    }

    /**
     * 将收件人或抄送人列表转换成String
     *
     * @param mailArray 收件人/抄送人列表
     * @return
     */
    public 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 file 文件
     * @return
     */
    public static MimeBodyPart getAttachedBodyPart(File file) throws MessagingException,
            UnsupportedEncodingException {
        String filePath = file.getPath();
        String fileName = file.getName();
        MimeBodyPart attached = new MimeBodyPart();
        FileDataSource fds = new FileDataSource(filePath);
        attached.setDataHandler(new DataHandler(fds));
        attached.setFileName(MimeUtility.encodeWord(fileName));//处理附件文件的中文名问题
        return attached;
    }

    // 测试
    public static void main(String[] args) {
        File file = new File("/user/kaijiyu/test.txt");
        sendEmail(file,"test.txt","从163发送的邮件");
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值