Java Mail

/*

复杂邮件程序完整Java源码,支持添加附件,图片,HTML格式文本,支持远程WebService调用*/

package com.hx.mail;

import java.io.File;

import java.util.Map;

import javax.mail.Message.RecipientType;

/**

* MailServices 邮件接收发送接口定义类

*

* @author 380595305@qq.com

* Date 2010-05-11

* @version 1.0

*/

public interface HexiangMailService {

/**

* sendMail 发送邮件函数

*

* @param sender 是String类型,邮件发送者信息

* @param password 是String类型,邮件发送者密码

* @param addressee 是String类型,邮件接收者信息

* @param subject 是String类型,传入邮件主题

* @param text 是String类型,传入邮件消息

*/

void sendMail(String sender,String password,String addressee,String subject,String text) throws Exception;

/**

* sendMail 发送邮件函数

*

* @param sender 是String类型,邮件发送者信息

* @param password 是String类型,邮件发送者密码

* @param addressee 是String类型,邮件接收者信息

* @param subject 是String类型,传入邮件主题

* @param text 是String类型,传入邮件消息

* @param enclosures Map<String,File> 邮件附件

* @param copyToSends Map<String,RecipientType> 邮件抄送信息

*/

void sendMail(String sender,String password,String addressee,String subject,String text,Map<String,File> enclosures,Map<String,RecipientType> copyToSends) throws Exception;

/**

* sendMail 发送邮件函数

*

* @param sender 是String类型,邮件发送者信息

* @param password 是String类型,邮件发送者密码

* @param subject 是String类型,传入邮件主题

* @param imgs 是File[]类型,邮件正文中附件的图片信息

* @param htmlContent 是String类型,传入邮件消息正文

* @param enclosures Map<String,File> 邮件附件

* @param copyToSends Map<String,RecipientType> 邮件抄送信息

*/

void sendMail(String sender,String password,String subject,File[] imgs,String htmlContent,Map<String,File> enclosures,Map<String,RecipientType> copyToSends) throws Exception;

}

package com.hx.mail;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.io.UnsupportedEncodingException;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import java.util.Properties;

import java.util.Set;

import javax.activation.DataHandler;

import javax.activation.DataSource;

import javax.activation.FileDataSource;

import javax.mail.Address;

import javax.mail.Authenticator;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.Message.RecipientType;

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 javax.mail.internet.MimeUtility;

import org.codehaus.xfire.attachments.ByteDataSource;

/**

* HexiangMailServiceImpl 邮件接收发送接口实现类

*

* @author 380595305@qq.com

* Date 2010-05-11

* @version 1.0

*/

public class HexiangMailServiceImpl implements HexiangMailService {

/** MailboxType 邮箱类型 */

private static Map<String, String> MailboxTypes = null;

/** host 邮箱服务器类型 */

private String host = null;

/** sender 邮件发送者 */

private String sender = null;

/** addressee 邮件接收者 */

private String addressee = null;

/** subject 邮件主题 */

private String subject = null;

/** text 邮件消息 */

private String text = null;

public static void init() {

MailboxTypes = new HashMap<String, String>();

MailboxTypes.put("163", "smtp.163.com");

MailboxTypes.put("139", "smtp.139.com");

MailboxTypes.put("126", "smtp.126.com");

MailboxTypes.put("qq", "smtp.qq.com");

MailboxTypes.put("live", "smtp.live.cn");

MailboxTypes.put("msn", "smtp.msn.com");

MailboxTypes.put("kum", "mail.kum.net.cn");

MailboxTypes.put("hotmail", "smtp.hotmail.cn");

}

/**

* initialization 实例化类成员变量

*/

private void initialization(String sender, String addressee,

String subject, String text) {

this.sender = sender;

this.addressee = addressee;

this.subject = subject;

this.text = text;

this.host = getHost(sender);

// System.out.println("sender->"+this.sender+" |

// addressee->"+this.addressee+" | subject->"+this.subject+" |

// text->"+this.text+" | host->"+this.host);

}

/**

* getHost 获取目标邮箱服务器类型

*

* @param sender

* 是String类型,传入邮件发送者邮箱地址信息

* @return String 返回目标邮箱服务器类型

*/

private String getHost(String sender) {

String _host, _host_ = null;

_host = sender.substring(sender.indexOf("@") + 1, sender.indexOf("."));

if (MailboxTypes == null) {

init();

}

_host_ = MailboxTypes.get(_host);

// System.out.println(_host+" <--> "+_host_);

if (_host_ == null) {

// MailboxTypes.put(_host,"smtp."+_host+".com");

MailboxTypes.put(_host,

"smtp."

+ sender.substring(sender.indexOf("@") + 1, sender

.length()));

}

return MailboxTypes.get(_host);

}

public void sendMail(String sender, String password, String addressee,

String subject, String text) throws Exception {

initialization(sender, addressee, subject, text);

Properties props = System.getProperties();

{

props.put("mail.smtp.host", this.host);

props.put("mail.smtp.auth", "true");

}

ValidateAuther auther = new ValidateAuther(this.sender, password);

Session session = Session.getDefaultInstance(props, auther);

MimeMessage msg = new MimeMessage(session);

InternetAddress fromAddr = new InternetAddress(this.sender); // 发送者邮箱地址

InternetAddress toAddr = new InternetAddress(this.addressee); // 接收者邮箱地址

msg.setFrom(fromAddr);

msg.addRecipient(Message.RecipientType.TO, toAddr);

/**

* Message.RecipientType.TO -- 接收者 Message.RecipientType.CC -- 抄送

* Message.RecipientType.BCC --秘密抄送者

*/

msg.setSubject(this.subject); // 邮件主题

msg.setText(this.text); // 邮件信息

Transport.send(msg); // 发送邮件

}

public void sendMail(String sender, String password, String addressee,

String subject, String text, Map<String, File> enclosures,

Map<String, RecipientType> copyToSends) throws Exception {

initialization(sender, addressee, subject, text);

Properties props = System.getProperties();

{

props.put("mail.smtp.host", this.host);

props.put("mail.smtp.auth", "true");

}

ValidateAuther auther = new ValidateAuther(this.sender, password);

Session session = Session.getDefaultInstance(props, auther);

Message msg = new MimeMessage(session);

InternetAddress fromAddr = new InternetAddress(this.sender); // 发送者邮箱地址

InternetAddress toAddr = new InternetAddress(this.addressee); // 接收者邮箱地址ַ

msg.setFrom(fromAddr);

msg.addRecipient(Message.RecipientType.TO, toAddr);

msg.setSubject(this.subject); // 邮件主题

msg.setText(this.text); // 邮件信息

msg = setCopyToSends(msg, copyToSends); // 设置抄送信息

try {

MimeMultipart msgMultipart = new MimeMultipart("mixed"); // 创建邮件复杂体

msgMultipart = setEnclosureFile(msgMultipart, enclosures); // 设置附件信息

msg.setContent(msgMultipart); // 将邮件复杂体添加到邮件正文中

MimeBodyPart content = new MimeBodyPart(); // 创建邮件复杂体正文信息

msgMultipart.addBodyPart(content); // 将正文信息添加到复杂体中

MimeMultipart bodyMultipart = new MimeMultipart("related");

content.setContent(bodyMultipart);

MimeBodyPart htmlPart = new MimeBodyPart(); // 创建HTML文本域

bodyMultipart.addBodyPart(htmlPart); // 将HTML文本域添加到正文组合中

DataSource htmlDs = new ByteDataSource(this.text==null?"".getBytes():this.text.getBytes()); // 指定文本域,创建DataSource

DataHandler htmlDh = new DataHandler(htmlDs);

htmlPart.setDataHandler(htmlDh);

htmlPart.setContent(this.text, "text/html;charset=gbk");

msg.saveChanges(); // 生成邮件

String filePath = "d:\\demo1.eml";

OutputStream os = new FileOutputStream(filePath);

msg.writeTo(os);

os.close();

} catch (MessagingException e) {

e.printStackTrace();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

//	 Transport.send(msg); // 发送邮件

}

public void sendMail(String sender, String password, String subject,

File[] imgs, String htmlContent, Map<String, File> enclosures,

Map<String, RecipientType> copyToSends) throws Exception {

initialization(sender, addressee, subject, htmlContent);

Properties props = System.getProperties();

{

props.put("mail.smtp.host", this.host);

props.put("mail.smtp.auth", "true");

}

ValidateAuther auther = new ValidateAuther(this.sender, password);

Session session = Session.getDefaultInstance(props, auther);

Message msg = new MimeMessage(session);

InternetAddress fromAddr = new InternetAddress(this.sender); // 发送者邮箱地址

// InternetAddress toAddr = new InternetAddress(this.addressee); //

// 接收者邮箱地址ַ

msg.setFrom(fromAddr);

// msg.addRecipient(Message.RecipientType.TO, toAddr);

msg.setSubject(this.subject); // 邮件主题

// msg.setText(this.text); // 邮件信息

msg = setCopyToSends(msg, copyToSends); // 设置抄送信息

try {

MimeMultipart msgMultipart = new MimeMultipart("mixed"); // 创建邮件复杂体

msgMultipart = setEnclosureFile(msgMultipart, enclosures); // 设置附件信息

msg.setContent(msgMultipart); // 将邮件复杂体添加到邮件正文中

if (htmlContent != null || (imgs != null && imgs.length > 0)) {

MimeBodyPart content = new MimeBodyPart(); // 创建邮件复杂体正文信息

msgMultipart.addBodyPart(content); // 将正文信息添加到复杂体中

// 搭建正文组合架构 -- 创建正文复杂体<含有html文本和图片文件> //related --> 关联关系

MimeMultipart bodyMultipart = new MimeMultipart("related");

content.setContent(bodyMultipart);

StringBuffer htmlBuffer = new StringBuffer();

// 添加HTML文本域信息

// if (htmlContent != null) {

// htmlContent = htmlBuffer.toString();

MimeBodyPart htmlPart = new MimeBodyPart(); // 创建HTML文本域

bodyMultipart.addBodyPart(htmlPart); // 将HTML文本域添加到正文组合中

// DataSource htmlDs = new FileDataSource(htmlContent);//

// 指定文件域,创建DataSource

DataSource htmlDs = new ByteDataSource(htmlContent.getBytes()); // 指定文本域,创建DataSource

DataHandler htmlDh = new DataHandler(htmlDs); // DataHandler

// 文件包装数据类

htmlPart.setDataHandler(htmlDh);

// htmlPart.setContent(htmlContent,"text/html;charset=gbk");

// }

// 添加图片域信息

if (imgs != null && imgs.length > 0) {

htmlBuffer.append(htmlContent); // HTML格式文本域

for (int i = 0; i < imgs.length; i++) {

MimeBodyPart gifPart = new MimeBodyPart();

bodyMultipart.addBodyPart(gifPart); // 将图片域添加到正文组合中

DataSource gifDs = new FileDataSource(imgs[i]);

DataHandler gifDh = new DataHandler(gifDs);

gifPart.setDataHandler(gifDh);

gifPart.setFileName(MimeUtility

.encodeText(getFileName(imgs[i].getName())));

htmlBuffer.append("<img src='"

+ MimeUtility.encodeText(imgs[i].getName())

+ "'>"); // 将图片域加入到文本域中

gifPart.setHeader("Content-Location", MimeUtility

.encodeText(imgs[i].getName())); // 指定该图片(文件)路径从本地关联文件中找

}

}

htmlContent = htmlBuffer.toString();

// 设置正文文本域及文本类型

htmlPart.setContent(htmlContent, "text/html;charset=gbk");

}

msg.saveChanges(); // 生成邮件

String filePath = "d:\\demo2.eml";

OutputStream os = new FileOutputStream(filePath);

msg.writeTo(os);

os.close();

} catch (MessagingException e) {

e.printStackTrace();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

Transport.send(msg); // 发送邮件

}

// 获取邮件地址信息

public static Address[] getAddress(List<String> recpType)

throws AddressException, UnsupportedEncodingException {

if (recpType == null || recpType.isEmpty()) {

return null;

}

Address[] addrs = new Address[recpType.size()];

for (int i = 0; i < addrs.length; i++) {

String nickNameAccount = getNickName(recpType.get(i));

String[] nickName_account = nickNameAccount.split(",");

// System.out.println(nickName_account);

addrs[i] = new InternetAddress("\""

+ MimeUtility.encodeText("" + nickName_account[0] + "")

+ "\" <" + nickName_account[1] + ">");

}

return addrs;

}

// 获取邮箱账号昵称信息

public static String getNickName(String mailAccount) {

int index = mailAccount.lastIndexOf("<");

if (index == -1) { // 不含有昵称信息,未找到"<>"

// hexiang221@163.com

String nickName = mailAccount.substring(0, mailAccount

.lastIndexOf("@"));

return nickName + "," + mailAccount;

} else if (index == 0) { // 不含有昵称信息 但找到了"<>"

// <hexiang@163.com>

String nickName = mailAccount.substring(index + 1, mailAccount

.lastIndexOf("@"));

String account = mailAccount.substring(index + 1, mailAccount

.lastIndexOf(">"));

return nickName + "," + account;

} else if (index > 0) { // 含有昵称信息,并且找到了"<>"

String nickName = mailAccount.substring(0, index);

String account = mailAccount.substring(index + 1, mailAccount

.lastIndexOf(">"));

return nickName + "," + account;

}

return mailAccount;

}

// 获取附件显示名称

public static String getFileName(String filePath) {

String fileName = null; // ���

if (filePath == null || filePath.length() == 0) {

return null;

}

int index = filePath.lastIndexOf("/");

if (index == -1) {

return filePath;

}

fileName = filePath.substring(filePath.lastIndexOf("/") + 1);

int index2 = fileName.lastIndexOf("\\");

if (index2 == -1) {

return fileName;

}

return fileName.substring(filePath.lastIndexOf("\\"));

}

// 设置邮件附件信息

public static MimeMultipart setEnclosureFile(MimeMultipart msgMultipart,

Map<String, File> enclosures) throws MessagingException,

UnsupportedEncodingException {

if (enclosures == null || enclosures.isEmpty()) {

return msgMultipart;

}

if (msgMultipart == null) {

msgMultipart = new MimeMultipart("mixed"); // 创建邮件复杂体

}

Set<String> enclosureSet = enclosures.keySet();

Iterator<String> enclosureIter = enclosureSet.iterator();

while (enclosureIter.hasNext()) {

String attchFileName = enclosureIter.next();

MimeBodyPart attch = new MimeBodyPart();

msgMultipart.addBodyPart(attch);

File temEnclosureFile = enclosures.get(attchFileName);

DataSource ds = new FileDataSource(temEnclosureFile);

DataHandler dh = new DataHandler(ds);

attch.setDataHandler(dh);

attch.setFileName(MimeUtility

.encodeText(getFileName(attchFileName)));// 设置附件显示名称

}

return msgMultipart;

}

public static Message setCopyToSends(Message msg,

Map<String, RecipientType> copyToSends) throws AddressException,

UnsupportedEncodingException, MessagingException {

if (copyToSends == null) {

return msg;

}

Set<String> copyToSendSet = copyToSends.keySet();

Iterator<String> copyToSendIter = copyToSendSet.iterator();

List<String> to = new ArrayList<String>(); // 定义接收者账号信息集

List<String> cc = new ArrayList<String>(); // 定义抄送者账号信息集

List<String> bcc = new ArrayList<String>();// 定义秘密抄送者账号信息集

while (copyToSendIter.hasNext()) {

String address = copyToSendIter.next(); // 获取抄送者邮箱账号信息

RecipientType tmpRecipientType = copyToSends.get(address);

if (tmpRecipientType == RecipientType.TO) {

to.add(address);

}

if (tmpRecipientType == RecipientType.CC) {

cc.add(address);

}

if (tmpRecipientType == RecipientType.BCC) {

bcc.add(address);

}

}

// 获取接收者信息集

Address[] to_addrs = getAddress(to);

if (to_addrs != null) {

msg.setRecipients(MimeMessage.RecipientType.TO, to_addrs);

}

// 获取抄送者信息集

Address[] cc_addrs = getAddress(cc);

if (cc_addrs != null) {

msg.setRecipients(MimeMessage.RecipientType.CC, cc_addrs);

}

// 获取秘密抄送者信息集

Address[] bcc_addrs = getAddress(bcc);

if (bcc_addrs != null) {

msg.setRecipients(MimeMessage.RecipientType.BCC, bcc_addrs);

}

return msg;

}

}

/**

* ValidateAuther 邮件验证类,验证邮件发送者信息

*/

class ValidateAuther extends Authenticator {

/** 邮件发送者 */

private String sender;

/** 邮件接受者 */

private String password;

/**

* ValidateAuther 验证邮件发送者信息

*

* @param userName

* 是String类型,传入邮件发送者账户

* @param password

* 是String类型,传入邮件发送者账户密码

*/

public ValidateAuther(String sender, String password) {

this.sender = sender;

this.password = password;

}

/**

* getPasswordAuthentication 验证邮件发送者账户信息的函数

*

* @param userName

* 邮件发送者账户信息

* @param password

* 邮件发送者账户密码

* @return PasswordAuthentication 返回邮件发送者账户验证信息

*/

@Override

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(sender, password);

}

}


// 支持WebService远程调用

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://xfire.codehaus.org/config/1.0">

<service>

<name>HexiangMailService</name>

<serviceClass>com.hx.mail.HexiangMailService</serviceClass>

<implementationClass>com.hx.mail.HexiangMailServiceImpl</implementationClass>

<style>wrapped</style>

<use>literal</use>

<scope>application</scope>

</service>

</beans>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值