javamail的一些整理

admin 发布于:2010-03-17 13:59:00
阅读:loading
记得前年底为了实现javamail发送邮件可是问了多少个高手呀,汉哥,曾宪荣哥哥,等等。后来还是在哥哥们的帮忙下,我一不小心改了又改,甚至不知道怎么回事就可以发送了,起初发送的邮件只能是文本,现在慢慢的升级到可以发送html段落,附件,抄送,暗送,现在对其做一些个人总结吧。
首先我们在事实的业务中,可能会涉及到邮件激活呀,找回账号密码呀,等地方用到发送邮件,发送邮件可以发送文本、HTML网页(激活账号的连接地址),撑死了想给公司打个广告,把公司的logo当做邮件的附件一起发送过去,也就这些。其实发送邮件还是比较简单的,当然了运行这些当然不是为了在main方法中测试通过,而是需要通过容器Tomcat等来运行的,在eclipse下新建1个web工程,他的J2EE 1.4 Libraries下面导入的有发送邮件所需要的jar文件,如果发布到tomcat容器中,就没有这2个jar文件了,所以还是拷贝这2个jar到你的工程lib目录下面吧,activation.jar在JBoss目录下面找得到,也可直接拷贝这2个文件,目录结构如
图所示:
且看看下面的吧:
准备工作:
1、必须有可以正常登录的邮箱账户、密码,合法的用户。
本程序实现的功能:
1、成功发送邮件
2、发送html段落的文件,如发送一个含有JavaScript或iframe标记的文件。
3、发送邮件附件
4、可同时给多个人发送邮件,可不是那种循环多次执行发送邮件的方法。
5、可同时抄送给多个人、和暗抄送(密送)
源码如下:
说明:作为一些常量数据,我在这里采取的是写在接口里面,这个接口里面没有定义任何的抽象方法
下面的为实现类:
1、实现类需要导入的头文件:
此部分代码为设置邮件信息等。
说明:上图中红色标红的方法:mySendMail中,第一个参数为:Object类行的,但只对于String类型或String[]类型的有效,该参数表示接收邮件人的对象,如果为String类型的时候,则为1个接收人的邮件地址,如果为String[] 的时候,表示为多个邮件接收人的地址数组,之所以用instanceof对象,因为这样写的更加直观一点,实现的功能就不详说了,上面有,不要附件也可相应的去掉那一部分。
声明:理解了缘由,发送邮件还是比较简单的。
=======20130625分割线=======添加发送抄送人、暗抄送=====
邮件抄送的功能跟发送差不了多少,究其参数不一样而已,如果少了这个,终归是不完善。源码:
package com;
/**
*
* 发送邮件的参数对象
*
* @author chendd
*
*
*/
public class SendMailParams {
/**
*
* 邮件标题
*/
private String title;
/**
*
* 邮件内容
*/
private String content;
/**
*
* 发送附件地址
*/
private String attachmentPath;
/**
*
* 发送人
*/
private String fromAddress;
/**
*
* 接收人地址
*/
private String[] toAddress;
/**
*
* 抄送人
*/
private String[] ccAddress;
/**
*
* 密送人(暗抄送)
*/
private String[] bccAddress;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getAttachmentPath() {
return attachmentPath;
}
public void setAttachmentPath(String attachmentPath) {
this.attachmentPath = attachmentPath;
}
public String getFromAddress() {
return fromAddress;
}
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
public String[] getToAddress() {
return toAddress;
}
public void setToAddress(String[] toAddress) {
this.toAddress = toAddress;
}
public String[] getCcAddress() {
return ccAddress;
}
public void setCcAddress(String[] ccAddress) {
this.ccAddress = ccAddress;
}
public String[] getBccAddress() {
return bccAddress;
}
public void setBccAddress(String[] bccAddress) {
this.bccAddress = bccAddress;
}
}
package com;
import java.io.File;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
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;
import javax.mail.internet.MimeUtility;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import com.frame.base.utils.properties.PropertiesUtils;
import com.frame.base.utils.properties.enums.EnumProperties;
/**
* 发送邮件,可以发送html段落、本地附件、网络附件(需要修改一个地方)
* @author chendd
*
*/
public class MailUtil{
private static Properties props = null;
private static Properties propertys = PropertiesUtils.getInstance().getProperties(EnumProperties.APPLICATION);
static{
if(props == null){
props = System.getProperties();
props.setProperty("mail.smtp.host", propertys.getProperty("mail.smtp.server"));
props.setProperty("mail.smtp.auth", propertys.getProperty("mail.smtp.auth"));
props.setProperty("mail.smtp.host", propertys.getProperty("mail.smtp.host"));
}
}
/**
* 发送邮件
* @param params 发送邮件相关的参数对象
*/
public void mySendMail(SendMailParams params){
//根据属性,创建邮件会话
Session session = Session.getDefaultInstance(props);
//设置邮件发送时显示调试信息
session.setDebug(Boolean.valueOf(propertys.getProperty("mail.smtp.debug")));
Message msg = new MimeMessage(session);
Transport trans = null;
try{
//根据消息对象,设置邮件的发送人
InternetAddress fromAddress = new InternetAddress(propertys.getProperty("mail.user.address"));
msg.setFrom(fromAddress);
//设置邮件的接收人
String toAddress[] = params.getToAddress();
if(ArrayUtils.isEmpty(toAddress)){
throw new Exception("邮件接收人不能为空");
}else{
int lens = toAddress.length;
InternetAddress[] tos = new InternetAddress[lens];
for (int i = 0; i < lens; i++) {
tos[i] = new InternetAddress(toAddress[i]);
}
msg.setRecipients(Message.RecipientType.TO, tos);
}
String[] ccAddress = params.getCcAddress();
if(ccAddress != null && ccAddress.length > 0){
InternetAddress ccAdds[] = new InternetAddress[2];
for (int i = 0; i < ccAddress.length; i++) {
String address = ccAddress[i];
ccAdds[i] = new InternetAddress(address);
}
msg.setRecipients(Message.RecipientType.CC, ccAdds);
}
String[] bccAddress = params.getBccAddress();
if(bccAddress != null && bccAddress.length > 0){
InternetAddress bccAdds[] = new InternetAddress[2];
for (int i = 0; i < bccAddress.length; i++) {
String address = bccAddress[i];
bccAdds[i] = new InternetAddress(address);
}
msg.setRecipients(Message.RecipientType.BCC, bccAdds);
}
msg.setSubject(params.getTitle());// 设置主题
/**注意,这里的发送时间不能要,如果有则需要准确的时间,否则发送报错*/
//msg.setSentDate(new Date());// 设置发送时间
//添加邮件内容
Multipart multipart = new MimeMultipart();
BodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent("hello",propertys.getProperty("mail.content.type"));
multipart.addBodyPart(bodyPart);
//添加邮件附件
String attachmentPath = params.getAttachmentPath();
if(StringUtils.isNotEmpty(attachmentPath)){
File file = new File(attachmentPath);
FileDataSource fileData = new FileDataSource(file);
BodyPart bodyFile = new MimeBodyPart();
bodyFile.setDataHandler(new DataHandler(fileData));
//bodyFile.setDataHandler(new DataHandler(new URL("http://p1.qhimg.com/t0151320b1d0fc50be8.png")));//设置发送网络附件
bodyFile.setFileName(MimeUtility.encodeText(fileData.getName(),propertys.getProperty("mail.content.encoding"),"B"));
multipart.addBodyPart(bodyFile);
}
msg.setContent(multipart);
msg.saveChanges();
trans = session.getTransport("smtp");
trans.connect(propertys.getProperty("mail.smtp.server"), propertys.getProperty("mail.user.name"),propertys.getProperty("mail.user.pwd"));
trans.sendMessage(msg, msg.getAllRecipients());
}catch(Exception e){
e.printStackTrace();
}finally{
if(trans != null){
try {
trans.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
}
}
package com;
/**
*
* 测试发送邮件
*
* @author chendd
*
*
*/
public class TestSendMail {
public static void main(String[] args) {
MailUtil mail = new MailUtil();
SendMailParams params = new SendMailParams();
params.setToAddress(new String[] { "271069593@qq.com" });
params.setTitle("邮件标题");
// 设置其他的参数:附件、html段落、抄送信息等
mail.mySendMail(params);
}
}
--------------相关的配置文件
#javamail的相关配置
mail.smtp.server = smtp.163.com
mail.smtp.auth = true
mail.smtp.host = 25
mail.smtp.debug = true
mail.user.address = wwwchendonglisahao@163.com
mail.user.name = wwwchendonglisahao
mail.user.pwd = 密码(******)
mail.content.type = text/html;chartset=utf-8
mail.content.encoding = utf-8
点赞