最近公司需要写一个通用一点的邮件发送功能,暂时主要是完成通用的验证后给顾客发送一个连接之类的纯文本消息,所以自己在java官网巴拉巴拉看了一通,瞎整了一个简单的java邮件发送功能,进过验证,功能简单但是效果还行,通过qq,163,outlook等邮箱服务器互发都ok,主要是,可以一对多发送。jar包就是很简单的javax.mail.jar
package javamail;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.AuthenticationFailedException;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.sun.mail.util.MailConnectException;
public class SendMailImpl implements SendMail{
public SendMailResult sendMail(String host,int port,String username,
String password,String subject,String contentType,
Date date,String header,Object contents,Address from,InternetAddress[] toUsers){
SendMailResult result = new SendMailResult();
if(isValidInput(result, host, username, port,from,toUsers))
{
Properties prop = mailConfig(true,true,host,username,port);
Session session = Session.getInstance(prop); //根据prop配置创建一个新的session对象
try {
Transport transport = session.getTransport();
transport.connect(host,port,username,password); //建立和邮箱服务器的链接
MimeMessage message = createMessage(session, from, toUsers, header, subject, contents, contentType, date);
transport.sendMessage(message,toUsers); //发送邮件
transport.close();
} catch (NoSuchProviderException e) {
result.setReturnCode(7);
// e.printStackTrace();
return result;
}catch (MessagingException e) {
System.out.println("host:"+host+" port:" +port+" username:"+username+" password:"+password);
if(e instanceof MailConnectException){
result.setReturnCode(6);
}else if(e instanceof AuthenticationFailedException){
result.setReturnCode(8);
}
else
result.setReturnCode(7);
// e.printStackTrace();
return result;
}
return result;
}else{
return result;
}
}
/**
* toUsers 必须是逗号隔开的String字符串
* @param toUsers
* @param date
* @param header
* @param subject
* @param contents
* @return
*/
public SendMailResult sendMailWithDefaultSetting(String toUsers,Date date,String header,String subject,String contents)
{
SendMailResult result =new SendMailResult();
if(toUsers!=null && toUsers.length()>0)
{
try{
InternetAddress[] to=InternetAddress.parse(toUsers);
result = sendMail(SendMail.HOST, SendMail.PORT, SendMail.SYSTEM_USER,SendMail.SYSTEM_USER_PASSWORD,
subject, SendMail.CONTENT_TYPE,date, header, contents, new InternetAddress(SendMail.SYSTEM_USER_ADDRESS),to);
}catch(AddressException e){
result.setReturnCode(5);
}
}
return result;
}
/**
* 邮箱发送方初始配置信息
* @param isDebug
* @param isStrict
* @param hostAddress
* @param username
* @param port
* @return
*/
private Properties mailConfig(boolean isDebug,boolean isStrict,String hostAddress,String username,int port){
Properties prop = new Properties();
String debug = (isDebug)?"true":"false";
String strict = (isStrict)?"true":"false";
hostAddress=(hostAddress==null)? SendMail.HOST : hostAddress;
String protocol=SendMail.DEFAULT_PROTOCOL; //设置发送邮件协议为smtp
port=(port<=0)? SendMail.PORT : port;
username=(hostAddress==null)? SendMail.SYSTEM_USER:username;
prop.setProperty("mail.debug",debug); //是否开启调试
prop.setProperty("mail.mime.address.strict", strict); //邮箱地址是否严格检查
prop.setProperty("mail.protocol.host", hostAddress); //设置邮箱发送服务器地址
prop.setProperty("mail.transport.protocol", protocol); //设置邮箱服务器发送协议smtp
prop.setProperty("mail.protocol.user", username); //设置发送方
prop.setProperty("mail.protocol.port", String.valueOf(port)); //设置邮箱服务器发送端口
return prop;
}
/**
* 构成邮件体的通用方法
* @param session
* @param from
* @param toUsers
* @param header
* @param subject
* @param contents
* @param contentType
* @param sendDate
* @return
*/
private MimeMessage createMessage(Session session,Address from,InternetAddress[] toUsers,String header,String subject,Object contents,String contentType,Date sendDate){
MimeMessage message = new MimeMessage(session); //创建发送邮件体
try {
message.addFrom(new Address[]{from});
message.addHeader(header, header);
message.addRecipients(Message.RecipientType.TO, toUsers);
message.setSubject(subject);
message.setContent(contents, contentType);
if(sendDate.before(new Date())) //如果发送时间为小于当前时间,设为立即时间发送
sendDate = new Date();
message.setSentDate(sendDate); //设定发送时间
} catch (MessagingException e) {
e.printStackTrace();
}
return message;
}
private boolean isValidInput(SendMailResult result,String host,String username,int port,Address from,Address[] to){
if(host==null||host.equals("")){
result.setReturnCode(1);
result.setReturnMessage("server adress missing !");
return false;
}else if(username==null||username.equals(""))
{
result.setReturnCode(2);
return false;
}else if(port<=0)
{
result.setReturnCode(3);
return false;
}else if(from==null){
result.setReturnCode(4);
return false;
}else if(to==null||to.length<1){
result.setReturnCode(5);
return false;
}
return true;
}
public static void main(String[] args) throws Exception {
SendMailResult result = new SendMailImpl().sendMail("mail.xx.com",25, "username","password","java mail test!","text/plain; charset=utf-8",
new Date(),"java mail test!","http://www.baidu.com",new InternetAddress("
[email protected]"),new InternetAddress[]{new InternetAddress("
[email protected]"),new InternetAddress("
[email protected]")});
System.out.println(result);
Thread.sleep(1000);
result = new SendMailImpl().sendMailWithDefaultSetting("
[email protected],
[email protected],
[email protected]", new Date(), "", "javamail test!!", "hello 我用自己的程序给你发邮件了咯!");
System.out.println(result);
}
}
package javamail;
import java.util.Date;
import javax.mail.Address;
import javax.mail.internet.InternetAddress;
public interface SendMail {
public static String HOST="xx";
public static String SYSTEM_USER="xx";
public static String SYSTEM_USER_ADDRESS="
[email protected]";
public static String SYSTEM_USER_PASSWORD="xx";
public static String DEFAULT_ENCODING="base64";
public static String DEFAULT_CHARSET="UTF-8";
public static String DEFAULT_PROTOCOL="smtp";
public static boolean SMTP_AUTH = false;
public static boolean ISDEBUG=false;
public static int PORT=25; //不同邮箱端口不同
public static String CONTENT_TYPE="text/plain;charset=utf-8";
/**
* 这个方法包含发送邮件需要配置的所有参数(暂时发送邮件功能不包含附件)
* @param host
* @param port
* @param username
* @param password
* @param subject
* @param contentType
* @param date
* @param header
* @param contents
* @param from
* @param toUsers
* @return
*/
public SendMailResult sendMail(String host,int port,String username,
String password,String subject,String contentType,
Date date,String header,Object contents,Address from,InternetAddress[] toUsers);
/**
* 这个方法根据默认系统配置发送邮件给接收方
* @param toUsers
* @param date
* @param header
* @param subject
* @param contents
* @return
*/
public SendMailResult sendMailWithDefaultSetting(String toUsers,Date date,String header,String subject,String contents);
}
package javamail;
public class SendMailResult {
/**
* returncode 1:服务器地址不存在 ; 2 发送方用户名不存在 3 邮件服务器端口设置不存在 4 发送方地址不存在 5 接收方地址不存在或错误
* 6 邮件服务器连接不上,服务器配置失败 7.系统创建邮箱服务失败
*
*
*/
private int returnCode; //邮件发送返回码
private String returnMessage; //返回的错误信息
public SendMailResult(){
this.returnCode=0;
this.returnMessage="SUCCESS";
}
public SendMailResult(int returnCode, String returnMessage) {
super();
this.returnCode = returnCode;
this.returnMessage = returnMessage;
}
public void setResult(int returnCode,String returnMessage){
this.returnCode = returnCode;
this.returnMessage = searchReturnMessage(returnCode);
}
private String searchReturnMessage(int returnCode){
String result=null;
switch(returnCode){
case 0: result="SUCCESS";
case 1: result="server adress missing !";break;
case 2: result="username missing !";break;
case 3: result="port missing !";break;
case 4: result="sender missing !";break;
case 5: result="receiver missing or wrong!";break;
case 6: result="server connect error,check the server configration!";break;
case 7: result="system error!";break;
case 8: result="username password error !";break;
default: result="";
}
return result;
}
public int getReturnCode() {
return returnCode;
}
public void setReturnCode(int returnCode) {
this.returnCode = returnCode;
this.returnMessage=searchReturnMessage(returnCode); //给code赋值的同时给message赋值;
}
public String getReturnMessage() {
return returnMessage;
}
public void setReturnMessage(String returnMessage) {
this.returnMessage = returnMessage;
}
@Override
public String toString() {
return "ErrorCode:"+returnCode+" ErrorMessage:"+returnMessage;
}
}