发送邮件功能

基于ssl安全协议的邮件发送功能:

ssl:

SSL(Secure Sockets Layer 安全套接层),及其继任者传输层安全(Transport Layer Security,TLS)是为网络通信提供安全及数据完整性的一种安全协议。TLS与SSL在传输层对网络连接进行加密。

SSL协议提供的服务主要有:

1、认证用户和服务器,确保数据发送到正确的客户机和服务器;

2、加密数据以防止数据中途被窃取;

3、维护数据的完整性,确保数据在传输过程中不被改变。

建议您在设置邮箱时使用SSL协议,这样会保障您邮箱更安全的使用。

使用方法:当您选择了使用SSL协议时,请您同时修改各收/发件服务器端口号。

SSL是什么?如何使用?

package net.common.utils.common;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
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 org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.mail.util.MailSSLSocketFactory;

/**
*
* 类描述: 用于SSL邮件发送,QQ企业邮箱测试通过。
*
*/
public class SslMailUtil {

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

  private String account; // 登录用户名
  private String pass; // 登录密码
  private String host; // 服务器地址(邮件服务器)
  private String port; // 端口
  private String protocol = "smtp"; // 协议
  private boolean isDebug = false;// 是否开启debug模式

  public SslMailUtil(String account, String pass, String host, String port) {
    super();
    this.account = account;
    this.pass = pass;
    this.host = host;
    this.port = port;
  }

  class MyAuthenricator extends Authenticator {
    String u = null;
    String p = null;

    public MyAuthenricator(String u, String p) {
      this.u = u;
      this.p = p;
    }

    protected PasswordAuthentication getPasswordAuthentication() {
      return new PasswordAuthentication(u, p);
    }
  }

  /**
   * 发送邮件
   *
   * @param to
   *          收件人
   * @param subject
   *          主题
   * @param content
   *          内容
   */
  public void send(String to, String subject, String content) throws Exception {
    this.send(null, to, subject, content, null);
  }

  /**
   * 发送邮件
   *
   * @param to
   *          收件人
   * @param subject
   *          主题
   * @param content
   *          内容
   * @param attachment
   *          附件
   */
  public void send(String to, String subject, String content, List<File> attachment) throws Exception {
    this.send(null, to, subject, content, attachment);
  }

  /**
   * 发送邮件
   *
   * @param alias
   *          发件人别名
   * @param to
   *          收件人
   * @param subject
   *          主题
   * @param content
   *          内容
   * @param attachment
   *          附件
   */
  public void send(String alias, String to, String subject, String content, List<File> attachment) throws Exception {
    Properties properties = this.getProperties();
    // 使用SSL,企业邮箱必需, 开启安全协议
    try {
      // 邮件会话
      Session session = this.getSession(properties);
      // 设置邮件内容
      MimeMessage mimeMessage = this.getMimeMessage(session, alias, to, subject, content, attachment);
      // 发送邮件
      Transport.send(mimeMessage);
    } catch (Exception e) {
      logger.error(e.toString());
      throw e;
    }
  }

  private Properties getProperties() {
    Properties properties = new Properties();
    // 协议
    properties.setProperty("mail.transport.protocol", protocol);
    // 服务器
    properties.setProperty("mail.smtp.host", this.host);
    // 端口
    properties.setProperty("mail.smtp.port", this.port);
    // 使用smtp身份验证
    properties.setProperty("mail.smtp.auth", "true");
    properties.put("mail.smtp.ssl.enable", "true");
    return properties;
  }

  private Session getSession(Properties properties) throws Exception {
    MailSSLSocketFactory mailSSLSocketFactory = new MailSSLSocketFactory();
    mailSSLSocketFactory.setTrustAllHosts(true);
    properties.put("mail.smtp.ssl.socketFactory", mailSSLSocketFactory);
    Session session = Session.getDefaultInstance(properties, new MyAuthenricator(this.account, this.pass));
    session.setDebug(this.isDebug);
    return session;
  }

  private MimeMessage getMimeMessage(Session session, String alias, String to, String subject, String content,
      List<File> attachment) throws Exception {
    MimeMessage mimeMessage = new MimeMessage(session);
    // 如果没有设置别名,则默认为发件人的邮箱账号
    if (StringUtils.isBlank(alias)) {
      alias = this.account;
    }
    //发件人账号以及别名
    mimeMessage.setFrom(new InternetAddress(this.account, alias));
    // 收件人
    mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    // 主题
    mimeMessage.setSubject(subject);
    // 时间
    mimeMessage.setSentDate(new Date());
    // 容器类,可以包含多个MimeBodyPart对象
    Multipart multipart = new MimeMultipart();
    // MimeBodyPart可以包装文本,图片,附件
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    // HTML正文,可以添加多个附件
    mimeBodyPart.setContent(content, "text/html; charset=UTF-8");
    multipart.addBodyPart(mimeBodyPart);
    if (attachment != null && !attachment.isEmpty()) {
      for (File file : attachment) {
        // 添加图片&附件


if (file.exists() && file.isFile()) {
  mimeBodyPart = new MimeBodyPart();
  mimeBodyPart.attachFile(file);
  multipart.addBodyPart(mimeBodyPart);
}
      }
    }
    // 设置邮件内容
    mimeMessage.setContent(multipart);
    // 仅仅发送文本
    // mimeMessage.setText(content);
    mimeMessage.saveChanges();
    return mimeMessage;
  }

  /**
   * 获得:是否开启debug模式
   *
   * @return the isDebug
   */
  public final boolean isDebug() {
    return isDebug;
  }

原文地址:https://www.cnblogs.com/wwqqnn123456/p/7894682.html