Overview

本文主要参考了javamail发送邮件的简单实例这篇文章。
最近和Chris在做secretepdb这个项目时,用到了发送邮件这一功能(需要用到mail.jar这个包)。经过Chris指点和自己查阅资料,还是比较顺利地完成了这一模块,特此记录一下。
该模块包含3部分:发送器(SimpleMailSender),验证器(MyAuthenticator)action。其中发送器部分将model单独分离出来为MailSenderInfo.java

1.发送器(SimpleMailSender)

原程序中实现了两种邮件格式的发送,本项目仅取文本格式。

import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;      

public class SimpleMailSender  {      
    public boolean sendTextMail(MailSenderInfo mailInfo) {      
        Properties pro = mailInfo.getProperties(); 
        MyAuthenticator authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
        // 根据邮件会话属性和验证器构造一个发送邮件的session      
        Session sendMailSession = Session.getDefaultInstance(pro,authenticator);      
        try {      
            // 根据session创建一个邮件消息      
            Message mailMessage = new MimeMessage(sendMailSession);      
            // 创建邮件发送者地址      
            Address from = new InternetAddress(mailInfo.getFromAddress());      
            // 设置邮件消息的发送者      
            mailMessage.setFrom(from);      
            // 创建邮件的接收者地址,并设置到邮件消息中      
            Address to = new InternetAddress(mailInfo.getToAddress());      
            mailMessage.setRecipient(Message.RecipientType.TO,to);      
            // 设置邮件消息发送的时间      
            mailMessage.setSentDate(new Date());      
            // 设置邮件消息的主要内容      
            String mailContent = mailInfo.getContent();      
            mailMessage.setText(mailContent);      
            // 发送邮件      
            Transport.send(mailMessage);     
            return true;      
      } catch (MessagingException e) {      
          e.printStackTrace();      
      }      
      return false;      
    }      
}    

2.发送器(SimpleMailSender)model

import java.util.Properties;      
public class MailSenderInfo {      
    // 发送邮件的服务器的IP和端口      
    private String mailServerHost;      
    private String mailServerPort;      
    // 邮件发送者的地址      
    private String fromAddress;      
    // 邮件接收者的地址      
    private String toAddress;      
    // 登陆邮件发送服务器的用户名和密码      
    private String userName;      
    private String password;      
    // 邮件的文本内容      
    private String content;      
 
    public Properties getProperties(){      
        Properties p = new Properties();
        //这里我们选用的是SMTP服务器,也可以选择POP3等服务器,但是要注意配置文件要对应。      
        p.put("mail.smtp.host", mailServerHost);      
        p.put("mail.smtp.port", mailServerPort); 
        //验证类型为ture,否则会出现javax.mail.AuthenticationFailedException异常。
        p.put("mail.smtp.auth", "true");
        return p;      
    }
    /*
    这里是mailServerHost等7个model的getters和setters。
    */
}   

3.验证器(MyAuthenticator)

这个密码验证器必须要有否则会出现javax.mail.AuthenticationFailedException异常。

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
   
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);     
    }     
} 

4.Action

这里主要负责读取配置文件(serverInfo.properties)、前后台交互和执行发送。

4.1 提交(SubmissionAction)

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import service.MailSenderInfo;
import service.SimpleMailSender;

public class SubmissionAction extends ActionSupport {
//Used to store the results from DB and be fetched by JSP.
private String surname;
private String givenName;
private String organization;
private String email;

private String proteinName;
private String species;
private String geneName;
private String uniprotID;
private String molecularWeight;
private String evidence;
private String proteinSequence;
private String proteinFunction;
private String structure;
private String interaction;
private String proteinMutation;
private String ptSites;
private String functionDomain;
private String pathway;

//Begin Search Action Method
public String execute() {
    MailSenderInfo mailInfo = new MailSenderInfo();
    Properties pps = new Properties();
    //get the path of the properties file
    String path = ServletActionContext.getServletContext().getRealPath("/")+"WEB-INF/serverInfo.properties";
    try {
        pps.load(new FileInputStream(path));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    //根据key读取配置文件
    String host=pps.getProperty("MAILSERVERHOST");
    String port=pps.getProperty("MAILSERVERPORT");
    String userName=pps.getProperty("USERNAME");
    String password = pps.getProperty("PASSWORD");
    String fAddress = pps.getProperty("FROMADDRESS");
    String tAddress=pps.getProperty("TOADDRESS");
    
    mailInfo.setMailServerHost(host);//邮箱服务器      
    mailInfo.setMailServerPort(port);//邮箱端口   
    mailInfo.setUserName(userName);//发件人邮箱        
    mailInfo.setPassword(password);//您的邮箱密码      
    mailInfo.setFromAddress(fAddress);//发件人邮箱     
    mailInfo.setToAddress(tAddress);//收件人邮箱
    
    String content = "Surname: " + this.surname+"\n"
            +"Given Name: "+this.givenName+"\n"
            +"Organization: "+this.organization+"\n"
            +"Email: "+this.email+"\n"
            +"Protein Name: "+this.proteinName+"\n"
            +"Species: "+this.species+"\n"
            +"Gene Name: "+this.geneName+"\n"
            +"Uniprot ID: "+this.uniprotID+"\n"
            +"Molecular Weight: "+this.molecularWeight+"\n"
            +"Evidence: "+this.evidence+"\n"
            +"Protein Sequence: "+this.proteinSequence+"\n"
            +"Protein Function: "+this.proteinFunction+"\n"
            +"Structure: "+this.structure+"\n"
            +"Protein-Protein Interaction: "+this.interaction+"\n"
            +"Protein Mutation: "+this.proteinMutation+"\n"
            +"Post-translational sites: "+this.ptSites+"\n"
            +"Function Domain: "+this.functionDomain+"\n"
            +"Metabolic/signaling Pathway: "+this.pathway+"\n";
    mailInfo.setContent(content);      
    //发送邮件     
    SimpleMailSender sms = new SimpleMailSender();     
    sms.sendTextMail(mailInfo);//发送文体格式      
    return SUCCESS;
}

/*这里写上各个model的getters和setters*/
}

4.2 配置文件(serverInfo.properties)

配置文件编写很简单,就是等号(=)两边一一映射,而且不加引号(""),读取出来都是String类型。

MAILSERVERHOST=smtp.mxhichina.com//这里用的阿里云企业邮箱smtp服务器
MAILSERVERPORT=25
USERNAME=系统发件箱地址
PASSWORD=系统发件箱密码
FROMADDRESS=发件箱地址//最好和系统发件箱地址一致
TOADDRESS=收件人邮箱

读取配置文件有多种方法,可以参考java读取properties文件方法和对比这篇文章。