Package com.ourlinc.helloworld.model

Source Code of com.ourlinc.helloworld.model.Mail

package com.ourlinc.helloworld.model;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
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.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 com.ourlinc.helloworld.EmailConfig;
import com.ourlinc.helloworld.util.WebUtils;
import com.ourlinc.swift.util.Misc;

/**
* 该类用来发送邮件,暂时关闭SSL支持
*
* @author lipeiying
*
*/
public class Mail {
  private Session session = null;
  private Properties properties = System.getProperties();
  private Authenticator authenticator = null;
  private HashMap<String, String> mailAttachment = new HashMap<String, String>();

  public static void main(String[] args) {
   
  }

  /**
   * 使用配置文件配置邮件服务器,权限认证,当不需要权限认证时参数可以为空
   *
   * @param user
   * @throws IOException
   */
  public Mail(String email, String password) {
    boolean needAuth = Boolean.valueOf(EmailConfig.getValue("needAuth"));
    String smtpHost = EmailConfig.getValue("smtpHost");
    setSMTPHost(smtpHost);
    if (needAuth) {
      enableAuth(email, password);
    } else {
      properties.put("mail.smtp.auth", "false");
    }
    session = getSession(needAuth);
  }

  /**
   * All in one setting
   */
  public Mail(String smtpHost, boolean needAuth, final String username,
      final String password, boolean isSSL, String sslPort) {
    setSMTPHost(smtpHost);
    if (isSSL) {
      enableSSL(sslPort);
    }
    if (needAuth) {
      enableAuth(username, password);
    }
    session = getSession(needAuth);
  }

  /**
   * 添加附件
   *
   * @param filePath
   */
  public void addAttachment(String filePath) {
    if (WebUtils.isEmptyString(filePath)) {
      throw new RuntimeException("[Error] Attachment filepath is empty!");
    }
    mailAttachment.put(filePath, new File(filePath).getName());
  }

  /**
   * 发送邮件,抛出异常表示发送失败
   *
   * @param fromAddress
   * @param toEmailAddresses
   * @param ccEmailAddresses
   * @param subject
   * @param content
   * @return
   * @throws MessagingException
   */
  public void send(String fromAddress, String[] toEmailAddresses,
      String[] ccEmailAddresses, String subject, String content)
      throws MessagingException {
    MimeMessage message = new MimeMessage(session);
    MimeMultipart multipart = new MimeMultipart();
    message.setSubject(subject);
    message.setRecipients(Message.RecipientType.TO,
        emailToInternetAddressArray(toEmailAddresses));
    message.setRecipients(Message.RecipientType.CC,
        emailToInternetAddressArray(ccEmailAddresses));
    message.addFrom(InternetAddress.parse(fromAddress));
    message.setSentDate(new Date());
    BodyPart mainBody = new MimeBodyPart();
    mainBody.setContent(content, "text/html;charset=gbk");
    multipart.addBodyPart(mainBody);
    for (Entry<String, String> e : mailAttachment.entrySet()) {
      BodyPart bodyPart = new MimeBodyPart();
      bodyPart.setDataHandler(new DataHandler(new FileDataSource(e
          .getKey())));
      bodyPart.setFileName(e.getValue());
      bodyPart.setHeader("Content-ID", e.getValue());
      multipart.addBodyPart(bodyPart);
    }
    message.setContent(multipart);
    message.saveChanges();
    Transport.send(message, message.getAllRecipients());
    Misc.getLogger().info("Send Mail success!");
  }

  private void setSMTPHost(String smtpHost) {
    if (smtpHost == null) {
      throw new RuntimeException("[Error] SMTP Host is empty!");
    }
    properties.setProperty("mail.smtp.host", smtpHost);
  }

  private Session getSession(boolean needAuth) {
    mailAttachment.clear();
    return needAuth ? session = Session.getInstance(properties,
        authenticator) : Session.getInstance(properties);
  }

  private void enableAuth(final String username, final String password) {
    if (username == null || password == null) {
      throw new RuntimeException("[Error] Username or password is empty!");
    }
    properties.put("mail.smtp.auth", "true");
    authenticator = new Authenticator() {
      protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
      }
    };
  }

  private void enableSSL(String sslPort) {
    if (WebUtils.isEmptyString(sslPort)) {
      throw new RuntimeException("[Error] SSL port is empty!");
    }
    properties.setProperty("mail.smtp.socketFactory.class",
        "javax.net.ssl.SSLSocketFactory");
    properties.setProperty("mail.smtp.socketFactory.fallback", "false");
    properties.setProperty("mail.smtp.port", sslPort);
    properties.setProperty("mail.smtp.socketFactory.port", sslPort);
  }

  private InternetAddress[] emailToInternetAddressArray(String[] email)
      throws AddressException {
    if (email == null || 0 == email.length) {
      return new InternetAddress[0];
    }
    InternetAddress[] addresses = new InternetAddress[email.length];
    for (int i = 0; i < email.length; i++) {
      addresses[i] = new InternetAddress(email[i]);
    }
    return addresses;
  }

}
TOP

Related Classes of com.ourlinc.helloworld.model.Mail

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.