JAVAMAIL 邮件发送器

邮件基本信息类

1、邮件信息类MailSenderInfo

package com.util.mail;   
/**   
* 发送邮件需要使用的基本信息 
*/    
import java.util.Properties;    
public class MailSenderInfo {    
    // 发送邮件的服务器的IP和端口    
    private String mailServerHost;    
    private String mailServerPort = "25";    
    // 邮件发送者的地址    
    private String fromAddress;    
    // 邮件接收者的地址    
    private String toAddress;    
    // 登陆邮件发送服务器的用户名和密码    
    private String userName;    
    private String password;    
    // 是否需要身份验证    
    private boolean validate = false;    
    // 邮件主题    
    private String subject;    
    // 邮件的文本内容    
    private String content;    
    // 邮件附件的文件名    
    private String[] attachFileNames;   
    /**   
      * 获得邮件会话属性   
      */    
    public Properties getProperties(){    
      Properties p = new Properties();    
      p.put("mail.smtp.host", this.mailServerHost);    
      p.put("mail.smtp.port", this.mailServerPort);    
      p.put("mail.smtp.auth", validate ? "true" : "false");    
      return p;    
    }    
    public String getMailServerHost() {    
      return mailServerHost;    
    }    
    public void setMailServerHost(String mailServerHost) {    
      this.mailServerHost = mailServerHost;    
    }   
    public String getMailServerPort() {    
      return mailServerPort;    
    }   
    public void setMailServerPort(String mailServerPort) {    
      this.mailServerPort = mailServerPort;    
    }   
    public boolean isValidate() {    
      return validate;    
    }   
    public void setValidate(boolean validate) {    
      this.validate = validate;    
    }   
    public String[] getAttachFileNames() {    
      return attachFileNames;    
    }   
    public void setAttachFileNames(String[] fileNames) {    
      this.attachFileNames = fileNames;    
    }   
    public String getFromAddress() {    
      return fromAddress;    
    }    
    public void setFromAddress(String fromAddress) {    
      this.fromAddress = fromAddress;    
    }   
    public String getPassword() {    
      return password;    
    }   
    public void setPassword(String password) {    
      this.password = password;    
    }   
    public String getToAddress() {    
      return toAddress;    
    }    
    public void setToAddress(String toAddress) {    
      this.toAddress = toAddress;    
    }    
    public String getUserName() {    
      return userName;    
    }   
    public void setUserName(String userName) {    
      this.userName = userName;    
    }   
    public String getSubject() {    
      return subject;    
    }   
    public void setSubject(String subject) {    
      this.subject = subject;    
    }   
    public String getContent() {    
      return content;    
    }   
    public void setContent(String textContent) {    
      this.content = textContent;    
    }    
}  

2、用户密码类MyAuthenticator

package com.util.mail;   

import javax.mail.*;   

public class MyAuthenticator extends Authenticator{   
    String userName=null;   
    String password=null;   

    public MyAuthenticator(){   
    }   
    public MyAuthenticator(String username, String password) {    
        this.userName = username;    
        this.password = password;    
    }    
    protected PasswordAuthentication getPasswordAuthentication(){   
        return new PasswordAuthentication(userName, password);   
    }   
}   

3、以HTML格式发送邮件 SimpleMailSender

package com.util.mail;   

import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
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;

/**   
* 简单邮件(不带附件的邮件)发送器   
*/    
public class SimpleMailSender  {    

    /**   
      * 以HTML格式发送邮件   
      * @param mailInfo 待发送的邮件信息   
     * @throws MessagingException 
      */    
    public  void sendHtmlMail(MailSenderInfo mailInfo) throws MessagingException{    
      // 判断是否需要身份认证    
      MyAuthenticator authenticator = null;   
      Properties pro = mailInfo.getProperties();   
      //如果需要身份认证,则创建一个密码验证器     
      if (mailInfo.isValidate()) {    
        authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());   
      }    
      // 根据邮件会话属性和密码验证器构造一个发送邮件的session    
      Session sendMailSession = Session.getDefaultInstance(pro,authenticator);    
      // 根据session创建一个邮件消息    
      Message mailMessage = new MimeMessage(sendMailSession);    
      // 创建邮件发送者地址    
      Address from = new InternetAddress(mailInfo.getFromAddress());    
      // 设置邮件消息的发送者    
      mailMessage.setFrom(from);    
      // 创建邮件的接收者地址,并设置到邮件消息中    
      Address to = new InternetAddress(mailInfo.getToAddress());    
      // Message.RecipientType.TO属性表示接收者的类型为TO    
      mailMessage.setRecipient(Message.RecipientType.TO,to);    
      // 设置邮件消息的主题    
      mailMessage.setSubject(mailInfo.getSubject());    
      // 设置邮件消息发送的时间    
      mailMessage.setSentDate(new Date());    
      // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象    
      Multipart mainPart = new MimeMultipart();    
      // 创建一个包含HTML内容的MimeBodyPart    
      BodyPart html = new MimeBodyPart();    
      // 设置HTML内容    
      html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");    
      mainPart.addBodyPart(html);    
      // 将MiniMultipart对象设置为邮件内容    
      mailMessage.setContent(mainPart);    
      // 发送邮件    
      Transport.send(mailMessage);    
    }    
}   

4、邮件工具类SentMailTool

package com.util.mail;

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

import org.activiti.engine.impl.util.json.JSONObject;
import org.apache.commons.lang.StringUtils;


public class SentMailTool {

    private Properties properties = new Properties();
    MailSenderInfo mailInfo = new MailSenderInfo();    
    private String mailHost = "";
    private String sender_username = "";
    private String sender_password = "";
    private String sender_nick = "";
    private String mailPort = "";
    private boolean mailAuth =false;

    /**
     * @Title:SentMailTool
     * @Description:初始化
     */
    public SentMailTool(){
        InputStream in = SentMailTool.class.getResourceAsStream("/portlet.properties");
        try {
            properties.load(in);
            this.mailHost = properties.getProperty("mail.smtp.host");
            this.mailPort = properties.getProperty("mail.smtp.port");
            this.mailAuth =Boolean.parseBoolean(properties.getProperty("mail.smtp.auth"));
            this.sender_username = properties.getProperty("mail.sender.username");
            this.sender_password = properties.getProperty("mail.sender.password");
            this.sender_nick = properties.getProperty("mail.sender.nick");
            //设置邮件参数
            mailInfo.setMailServerHost(this.mailHost);    
            mailInfo.setMailServerPort(this.mailPort);    
            mailInfo.setValidate(this.mailAuth);    
            mailInfo.setUserName(this.sender_username);    
            mailInfo.setPassword(this.sender_password);//您的邮箱密码    
            if(StringUtils.isNotBlank(this.sender_nick)){
                mailInfo.setFromAddress(sender_nick+" <"+this.sender_username+">");    
            }else{
                mailInfo.setFromAddress(this.sender_username);    
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 
     * @Title: toSendHtmlMail
     * @Description: 发送HTML格式的邮件
     * @param mailAddress   接受邮箱地址
     * @param title         邮件标题
     * @param message       邮件内容
     * @return
     * @return: boolean
     */
    public  JSONObject toSendHtmlMail(String mailAddress,String title,String message){

        JSONObject json=new JSONObject();
        try {
            mailInfo.setToAddress(mailAddress);    
            mailInfo.setSubject(title);    
            mailInfo.setContent(message);  
            //这个类主要来发送邮件   
            SimpleMailSender sms = new SimpleMailSender();   
            sms.sendHtmlMail(mailInfo);//发送html格式 
            json.put("result", true);
        }catch (Exception e) {
            e.printStackTrace();
            json.put("message", getErrorMessasge(e.getMessage()));
            json.put("result", false);
        }
        return json;
    }

    /**
     * 获取失败信息
     * @param message
     */
    private String getErrorMessasge(String message) {
         Map<String,String> map=new HashMap<String,String>();
         map.put("There are no DNS entries for the hostname, I cannot determine where to send this message", "检索不到接收方域名的邮件解析(MX记录)和域名解析(A记录)");
         map.put("Connection refused: connect.", "无法建立SMTP连接或者对方服务器忙");
         map.put("invalid address", "没有这个收件人");
         map.put("User unknown", "没有这个收件人");
         map.put("user is not found", "没有这个收件人");
         map.put("552Message size exceeds fixed limit", "您发给对方的信件大小超过了对方允许的范围");
         map.put("receiptor's mailbox is full(#5.5.4)", "对方邮箱已满");
         map.put("Quota exceed the hard limit for user ", "对方邮箱已满");
         map.put("Connected to remote host, but it does not like recipient.", "连接到接收方邮件服务器,但接收地址不存在");
         map.put("Connected to remote host, but sender was rejected.", "连接到接收方邮件服务器,但投递地址被拒绝。");
         map.put("Connected to remote host, but failed after I sent the message", "连接到接收方邮件服务器,但发送邮件失败。");
         map.put("Sorry, I couldn't find any hostnamed ", "没有这个主机。");
         map.put("553 Invalid sender", "投递方发信地址伪装,被对方邮局拒绝");
         map.put("550", "请检查收信人的邮件地址是否有误。");
         map.put("554 ", "发信服务器拒绝发送");
         map.put("timed out", "发送超时");
         boolean flag=false;
         for(String s:map.keySet()){
             if(message.contains(s)){
                 message=map.get(s);
                 flag=true;
             }
         }
         if(!flag){
             message="未知错误";
         }
         return message;
    }



}

5、 发送邮件服务器配置文件portlet.properties

#邮件服务器配置
#smtp 服务器
mail.smtp.host=smtp.163.com
#身份验证,默认true
mail.smtp.auth=true
#端口号
mail.smtp.port=25
#发送者的邮箱用户名
mail.sender.username=longchengguoke@163.com
#发送者的邮箱密码
mail.sender.password=123456asd
#发送者想要显示的昵称,选填
mail.sender.nick=Mr.cheng

6、备注:上边这个邮件服务器配置可以直接使用,如果密码不对可以找我要最新的授权码,也可以自己申请163邮箱服务器

猜你喜欢

转载自blog.csdn.net/mr_chinacheng/article/details/54409352