使用spring发送邮件例

使用javamail來發送信件的主要流程是由 web server 將 email 先傳送至 SMTP server
接著再由 smtp server 將此信件傳送出去
所以email會發送失敗主要可分為兩個情況
一是由web server 到 smtp server 這一段發生錯誤
二是由smtp server 到destination po 這一段發生錯誤
而使用javamail可以控制的就只有由 web server 到 smtp server 這一段的傳送
如果 smtp server 能夠正確的接收由 web server 傳送過來的 email
對使用javamail 的 web server 來說就是發送成功了
在第一種情況中主要會發生發送失敗的原因主要可能是web server 和 smtp server間的網路不通或是smtp server 需要authentication才能幫你發信

但一般來說email發送失敗的原因主要都是由第二種情況所產生的
像是錯誤的email address , 信箱爆滿, 防火牆或是防毒的blocking....等等
這些錯誤訊息只有smtp server端才會知道
使用javamail是沒有辦法得知這類形的發送錯誤
如果你真需要知道這類形的錯誤訊息
有一個做法就是去作退信處理

good luck


做了个spring发送纯文本文件以及发送带附件的邮件的例子,共享之。
1. SpringMail类
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;

import javax.mail.internet.MimeMessage;
import javax.mail.MessagingException;
import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.activation.FileDataSource;
import javax.activation.DataHandler;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.Multipart;

import java.util.List;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;

/** *//**
* spring的邮件发送例子
* @author Amigo Xie(xiexingxing1121@126.com)
* @since 2007/04/28 11:30
*/
public class SpringMail {

public static void main(String[] args) throws Exception {
ApplicationContext ctx = new FileSystemXmlApplicationContext(
"src/applicationContext.xml");
JavaMailSender sender = (JavaMailSender) ctx.getBean("mailSender");
SpringMail springMail = new SpringMail();

//测试发送只有文本信息的简单测试
springMail.sendTextMail(sender);

//测试发送带附件的邮件
springMail.sendMimeMessage(sender);
}

/** *//**
* 测试发送只有文本信息的简单测试
* @param sender 邮件发送器
* @throws Exception
*/
private void sendTextMail(JavaMailSender sender) throws Exception {
SimpleMailMessage mail = new SimpleMailMessage();
mail.setTo("xiexingxing1121@126.com");
mail.setFrom("xiexingxing1121@126.com");
mail.setSubject("test by amigo");
mail.setText("spring Mail的简单测试");
sender.send(mail);

System.out.println("成功发送文本文件!");
}

/** *//**
* 发送带附件的邮件
* @param sender 邮件发送器
* @throws Exception
*/
private void sendMimeMessage(final JavaMailSender sender) throws Exception {
//附件文件集合
final List files = new ArrayList();
MimeMessagePreparator mimeMail = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws MessagingException {
mimeMessage.setRecipient(Message.RecipientType.TO,
new InternetAddress("xiexingxing1121@126.com"));
mimeMessage.setFrom(new InternetAddress("xiexingxing1121@126.com"));
mimeMessage.setSubject("Spring发送带附件的邮件", "gb2312");

Multipart mp = new MimeMultipart();

//向Multipart添加正文
MimeBodyPart content = new MimeBodyPart();
content.setText("内含spring邮件发送的例子,请查收!");

//向MimeMessage添加(Multipart代表正文)
mp.addBodyPart(content);
files.add("src/SpringMail.java");
files.add("src/applicationContext.xml");

//向Multipart添加附件
Iterator it = files.iterator();
while(it.hasNext()) {
MimeBodyPart attachFile = new MimeBodyPart();
String filename = it.next().toString();
FileDataSource fds = new FileDataSource(filename);
attachFile.setDataHandler(new DataHandler(fds));
attachFile.setFileName(fds.getName());
mp.addBodyPart(attachFile);
}

files.clear();

//向Multipart添加MimeMessage
mimeMessage.setContent(mp);
mimeMessage.setSentDate(new Date());
}
};

//发送带附件的邮件
sender.send(mimeMail);

System.out.println("成功发送带附件邮件!");
}
}

2. spring的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host">
<value>smtp.126.com</value>
</property>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.timeout">25000</prop>
</props>
</property>
<property name="username">
<value>xiexingxing1121</value>
</property>
<property name="password">
<value><!-- 此处填写密码 --></value>
</property>
</bean>
</beans>
刚才发现一bug,当附件名为中文时,会出现中文乱码问题,对sendMimeMessage方法进行了部分修改,如下:
sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
files.add("src/SpringMail.java");
files.add("src/applicationContext.xml");
files.add("src/谢星星.xml");

//向Multipart添加附件
Iterator it = files.iterator();
while (it.hasNext()) {
MimeBodyPart attachFile = new MimeBodyPart();
String filename = it.next().toString();
FileDataSource fds = new FileDataSource(filename);
attachFile.setDataHandler(new DataHandler(fds));
attachFile.setFileName("=?GBK?B?"+enc.encode(fds.getName().getBytes())+"?=");
mp.addBodyPart(attachFile);
}
posted on 2007-04-28 13:23 阿蜜果 阅读(3995) 评论(6) 编辑 收藏 所属分类: Spring



FeedBack:
# re: 使用spring发送邮件例
2007-04-28 14:07 | 王凌华

:) 我直接用javamail也写了一个类似的东西。(ThreadPool实现的压力测试小工具),这里我有几问题:
a.
但是我用126的mailserver的时候,出现这样的错误:

javax.mail.MessagingException: Could not connect to SMTP host: smtp.126.com, port: 25
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:855)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:156)
at javax.mail.Service.connect(Service.java:256)
at javax.mail.Service.connect(Service.java:135)
at javax.mail.Service.connect(Service.java:87)
at com.sun.mail.smtp.SMTPTransport.connect(SMTPTransport.java:93)
at MailSender.run(MailSender.java:172)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)


我用我公司的的两台mailserver都可以顺畅的发mail。

回复 更多评论

# re: 使用spring发送邮件例[未登录]
2007-04-28 15:03 | ronghai

看看是不是需要SSl验证 回复 更多评论

# re: 使用spring发送邮件例
2007-04-29 12:47 | 王凌华

据我所知,gmail的发送和接受是需要ssl验证的.

所以我刚才花了点时间去看了一下javamail里面ssl里面是怎么写的.
这是代码片段:

----------------------------------------------------------------------------------
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.socketFactory.fallback", "false");
// props.put("mail.smtp.debug", "true");
prop.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
prop.put("mail.smtp.port", "465");
prop.put("mail.smtp.socketFactory.port", "465");
prop.put("mail.smtps.auth", needAuth);
prop.put("mail.transport.protocol", "smtp");
prop.put("mail.smtp.host", mailServer);
----------------------------------------------------------------------------------

----------------------------------------------------------------------------------
SMTPTransport transport = (SMTPTransport) session
.getTransport("smtps");
----------------------------------------------------------------------------------
我的努力换来的是发送期间的TimeOut, 没有任何迹象表明代码哪里有问题.
... ... ...

最后我终于明白这里用到了465 port. 而我在公司内网内,这个port默认情况下是禁用的. :) -真倒霉. 回复 更多评论

# re: 使用spring发送邮件例
2007-04-29 12:50 | 王凌华

顺便贴出gmail的配置URL. 大家有兴趣也可以试试:

http://mail.google.com/support/bin/answer.py?answer=13287 回复 更多评论

# spring发送内嵌邮件的图片无法正常显示的问题
2007-09-14 08:27 | LG

import java.io.File;
import javax.mail.MessagingException;
import javax.mail.internet.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;


public class SpringMail {
public static void main(String[] args) throws Exception{

ApplicationContext ctx=new FileSystemXmlApplicationContext("src/applicationContext.xml");

JavaMailSenderImpl sender = (JavaMailSenderImpl)ctx.getBean("mailSender");


SpringMail springMail=new SpringMail();

springMail.sendInit(sender);
}

private void sendInit(JavaMailSenderImpl sender) throws MessagingException {

MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message,true,"GB2312");
helper.setFrom("dongweiyi1125@sina.com");
helper.setTo("dongweiyi1125@sina.com");
helper.setSubject("Test");
helper.setText("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\"></head><body><h1><a href='#'>郁闷!"
+ "<img src=\"cid:identifier\"></body></html>", true);

FileSystemResource res = new FileSystemResource(new File("c:/weiyi.jpg"));
helper.addInline("identifier", res);


try {
sender.send(message);
} catch (MailException e) {
e.printStackTrace();
}
System.out.println("成功发送内嵌文件");
}
}


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">


<beans>
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host">
<value>smtp.sina.com</value>
</property>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.timeout">25000</prop>
</props>
</property>
<property name="username">
<value>dongweiyi1125</value>
</property>
<property name="password">
<value>邮箱密码</value>
</property>
</bean>
</beans>


以上代码给新浪邮箱发送邮件时图片总不能正常显示,但是给QQ邮箱发送邮件时却可以正常显示,不知什么原因,请大虾出来帮忙…… 回复 更多评论

# re: 使用spring发送邮件例 AuthenticationFailedException
2008-07-12 08:51 | Jayden

和上面的代码一样 怎么老是报AuthenticationFailedException 异常啊 回复 更多评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值