javamail发送qq邮件用新浪邮箱发送邮箱,为什么一直证不通过。

posts - 293,&
comments - 1547,&
trackbacks - 0
&&&&&做了个spring发送纯文本文件以及发送带附件的邮件的例子,共享之。&&&&&&1. SpringMail类&&&&&
import&org.springframework.context.ApplicationCimport&org.springframework.context.support.FileSystemXmlApplicationCimport&org.springframework.mail.SimpleMailMimport&org.springframework.mail.javamail.JavaMailSimport&org.springframework.mail.javamail.MimeMessagePimport&javax.mail.internet.MimeMimport&javax.mail.MessagingEimport&javax.mail.Mimport&javax.mail.internet.InternetAimport&javax.activation.FileDataSimport&javax.activation.DataHimport&javax.mail.internet.MimeMimport&javax.mail.internet.MimeBodyPimport&javax.mail.Mimport&java.util.Limport&java.util.ArrayLimport&java.util.Dimport&java.util.I/**&*//**&*&spring的邮件发送例子&*&@author&Amigo&Xie(xiexingxing1121&#)&*&@since&&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&#");&&&&&&&&mail.setFrom("xiexingxing1121&#");&&&&&&&&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&#"));&&&&&&&&&&&&&&&&mimeMessage.setFrom(new&InternetAddress("xiexingxing1121&#"));&&&&&&&&&&&&&&&&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&&/value&&&&&&&&&&/property&&&&&&&&&&property&name="javaMailProperties"&&&&&&&&&&&&&&props&&&&&&&&&&&&&&&&&&prop&key="mail.smtp.auth"&true&/prop&&&&&&&&&&&&&&&&&&prop&key="mail.smtp.timeout"&<span style="COLOR: #000&/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);&&&&&&&&&&&&&&&&}
阅读(15318)
&re: 使用spring发送邮件例
:) 我直接用javamail也写了一个类似的东西。(ThreadPool实现的压力测试小工具),这里我有几问题:
a.
但是我用126的mailserver的时候,出现这样的错误:
javax.mail.MessagingException: Could not connect to SMTP host: , 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发送邮件例[未登录]
看看是不是需要SSl验证&&&&&&
&re: 使用spring发送邮件例
据我所知,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发送邮件例
顺便贴出gmail的配置URL. 大家有兴趣也可以试试:&&&&&&
&spring发送内嵌邮件的图片无法正常显示的问题
import java.io.F
import javax.mail.MessagingE
import javax.mail.internet.*;
import org.springframework.context.ApplicationC
import org.springframework.context.support.FileSystemXmlApplicationC
import org.springframework.core.io.FileSystemR
import org.springframework.mail.MailE
import org.springframework.mail.javamail.JavaMailSenderI
import org.springframework.mail.javamail.MimeMessageH
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&#&);
helper.setTo(&dongweiyi1125&#&);
helper.setSubject(&Test&);
helper.setText(&&html&&head&&meta http-equiv=\&Content-Type\& content=\&text/ 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);
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& &
&bean id=&mailSender& class=&org.springframework.mail.javamail.JavaMailSenderImpl&&
&property name=&host&&
&value&&/value&
&/property&
&property name=&javaMailProperties&&
&prop key=&mail.smtp.auth&&true&/prop&
&prop key=&mail.smtp.timeout&&25000&/prop&
&/property&
&property name=&username&&
&value&dongweiyi1125&/value&
&/property&
&property name=&password&&
&value&邮箱密码&/value&
&/property&
&/bean&
&/beans&
以上代码给新浪邮箱发送邮件时图片总不能正常显示,但是给QQ邮箱发送邮件时却可以正常显示,不知什么原因,请大虾出来帮忙……&&&&&&
&re: 使用spring发送邮件例 AuthenticationFailedException
和上面的代码一样 怎么老是报AuthenticationFailedException 异常啊&&&&&&
&re: 使用spring发送邮件例
谢谢,楼主分享~~&&&&&&
25262728293031123910131516171819202223293012345
&&&&&&生活将我们磨圆,是为了让我们滚得更远&#8212;&#8212;&#8220;圆&#8221;来如此。&&&&& 我的作品:&&&&&&&&&&&&&&&(2012年1月出版)&&&&&&&&&&(2010年5月出版)&&&&&
留言簿(242)
积分与排名
阅读排行榜
评论排行榜
60天内阅读排行用Java发送邮件
闲来无事,写了个Java发送邮件的例子,做个记录,以便以后不时之需。
要用Java发送邮件,除过JDK本身的jar包之外,还需要两个额外的jar包:JavaMail和JAF。当然,如果你使用的JavaEE的JDK,那就不用单独去网上下载了,因为JavaEE的JDK中已经自带了这两个jar包。如果你使用的是JavaSE的JDK,那么你需要去Oracle的网站上下载这两个jar包。JavaMail
1.4.5 jar包下载地址是:,JAF
1.1.1 jar包下载地址是:。将这两个Zip包下载下来之后解压,将里边的几个jar包(mail.jar、dsn.jar、imap.jar、mailapi.jar、pop3.jar、smtp.jar和activation.jar)全部加到工程里边。下边就可以开始写程序了。加上测试程序,一共有4个类。
第一个类:MailSenderInfo.java,记录发送邮件所需的各种信息,如发送邮件服务器的地址、端口号、发件人邮箱、收件人邮箱等等。代码如下:
package com.test.
import java.util.P
public class MailSenderInfo {
&// 发送邮件的服务器的IP(或主机地址)
&private String mailServerH
&// 发送邮件的服务器的端口
&private String mailServerPort = "25";
&// 发件人邮箱地址
&private String fromA
&// 收件人邮箱地址
&private String toA
&// 登陆邮件发送服务器的用户名
&private String userN
&// 登陆邮件发送服务器的密码
&private S
&// 是否需要身份验证
&private boolean validate =
&// 邮件主题
&private S
&// 邮件的文本内容
&private S
&// 邮件附件的文件名
&private String[] attachFileN
&public Properties getProperties() {
&&Properties p = new Properties();
&&p.put("mail.smtp.host", this.mailServerHost);
&&p.put("mail.smtp.port", this.mailServerPort);
&&p.put("mail.smtp.auth", validate ? "true" : "false");
&public String getMailServerHost() {
&&return mailServerH
&public void setMailServerHost(String mailServerHost) {
&&this.mailServerHost = mailServerH
&public String getMailServerPort() {
&&return mailServerP
&public void setMailServerPort(String mailServerPort) {
&&this.mailServerPort = mailServerP
&public boolean isValidate() {
&public void setValidate(boolean validate) {
&&this.validate =
&public String[] getAttachFileNames() {
&&return attachFileN
&public void setAttachFileNames(String[] fileNames) {
&&this.attachFileNames = fileN
&public String getFromAddress() {
&&return fromA
&public void setFromAddress(String fromAddress) {
&&this.fromAddress = fromA
&public String getPassword() {
&public void setPassword(String password) {
&&this.password =
&public String getToAddress() {
&&return toA
&public void setToAddress(String toAddress) {
&&this.toAddress = toA
&public String getUserName() {
&&return userN
&public void setUserName(String userName) {
&&this.userName = userN
&public String getSubject() {
&public void setSubject(String subject) {
&&this.subject =
&public String getContent() {
&public void setContent(String textContent) {
&&this.content = textC
第二个类:MyAuthenticator.java,邮箱用户名和密码认证器。代码如下:
package com.test.
import javax.mail.A
import javax.mail.PasswordA
public class MyAuthenticator extends Authenticator {
&String userName =
&String password =
&public MyAuthenticator() {
&public MyAuthenticator(String username, String password) {
&&this.userName =
&&this.password =
&protected PasswordAuthentication getPasswordAuthentication() {
&&return new PasswordAuthentication(userName, password);
第三个类:SimpleMailSender.java,用来发送邮件类。代码如下:
package com.test.
import java.util.D
import java.util.P
import javax.mail.A
import javax.mail.BodyP
import javax.mail.M
import javax.mail.MessagingE
import javax.mail.M
import javax.mail.S
import javax.mail.T
import javax.mail.internet.InternetA
import javax.mail.internet.MimeBodyP
import javax.mail.internet.MimeM
import javax.mail.internet.MimeM
public class SimpleMailSender {
&public boolean sendTextMail(MailSenderInfo mailInfo) {
&&// 判断是否需要身份认证
&&MyAuthenticator authenticator =
&&Properties pro = mailInfo.getProperties();
&&if (mailInfo.isValidate()) {
&&&// 如果需要身份认证,则创建一个密码验证器
&&&authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
&&// 根据邮件会话属性和密码验证器构造一个发送邮件的session
&&Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
&&&// 根据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.setSubject(mailInfo.getSubject());
&&&// 设置邮件消息发送的时间
&&&mailMessage.setSentDate(new Date());
&&&// 设置邮件消息的主要内容
&&&String mailContent = mailInfo.getContent();
&&&mailMessage.setText(mailContent);
&&&// 发送邮件
&&&Transport.send(mailMessage);
&&} catch (MessagingException ex) {
&&&ex.printStackTrace();
&public static boolean sendHtmlMail(MailSenderInfo mailInfo) {
&&// 判断是否需要身份认证
&&MyAuthenticator authenticator =
&&Properties pro = mailInfo.getProperties();
&&// 如果需要身份认证,则创建一个密码验证器
&&if (mailInfo.isValidate()) {
&&&authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
&&// 根据邮件会话属性和密码验证器构造一个发送邮件的session
&&Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
&&&// 根据session创建一个邮件消息
&&&Message mailMessage = new MimeMessage(sendMailSession);
&&&// 创建邮件发送者地址
&&&Address from = new InternetAddress(mailInfo.getFromAddress());
&&&// 设置邮件消息的发送者
&&&mailMessage.setFrom(from);
&&&// 创建邮件的接收者地址,并设置到邮件消息中
&&&Address to = new InternetAddress(mailInfo.getToAddress());
&&&// Message.RecipientType.TO属性表示接收者的类型为TO
&&&mailMessage.setRecipient(Message.RecipientType.TO, to);
&&&// 设置邮件消息的主题
&&&mailMessage.setSubject(mailInfo.getSubject());
&&&// 设置邮件消息发送的时间
&&&mailMessage.setSentDate(new Date());
&&&// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
&&&Multipart mainPart = new MimeMultipart();
&&&// 创建一个包含HTML内容的MimeBodyPart
&&&BodyPart html = new MimeBodyPart();
&&&// 设置HTML内容
&&&html.setContent(mailInfo.getContent(), "text/ charset=utf-8");
&&&mainPart.addBodyPart(html);
&&&// 将MiniMultipart对象设置为邮件内容
&&&mailMessage.setContent(mainPart);
&&&// 发送邮件
&&&Transport.send(mailMessage);
&&} catch (MessagingException ex) {
&&&ex.printStackTrace();
第三个类:SendMailDemo.java,发送邮件的测试类。代码如下:
package com.test.
public class SendMailDemo {
&public static void main(String[] args) {
&&// 设置邮件服务器信息
&&MailSenderInfo mailInfo = new MailSenderInfo();
&&mailInfo.setMailServerHost("");
&&mailInfo.setMailServerPort("25");
&&mailInfo.setValidate(true);
&&// 邮箱用户名
&&mailInfo.setUserName("zhangsan");
&&// 邮箱密码
&&mailInfo.setPassword("zhangsanpass");
&&// 发件人邮箱
&&mailInfo.setFromAddress("zhangsan");
&&// 收件人邮箱
&&mailInfo.setToAddress("lisi");
&&// 邮件标题
&&mailInfo.setSubject("测试Java程序发送邮件");
&&// 邮件内容
&&StringBuffer buffer = new StringBuffer();
&&buffer.append("JavaMail 1.4.5 jar包下载地址:");
&&buffer.append("JAF 1.1.1 jar包下载地址:");
&&mailInfo.setContent(buffer.toString());
&&// 发送邮件
&&SimpleMailSender sms = new SimpleMailSender();
&&// 发送文体格式
&&sms.sendTextMail(mailInfo);
&&// 发送html格式
&&SimpleMailSender.sendHtmlMail(mailInfo);
&&System.out.println("邮件发送完毕");
至此,Java邮件发送程序已经写完,当然了,这只是实现了最基本的功能。经过测试,可以将邮件发送出去。
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。JavaMail使用_百度文库
两大类热门资源免费畅读
续费一年阅读会员,立省24元!
评价文档:
JavaMail使用
阅读已结束,如果下载本文需要使用
想免费下载本文?
把文档贴到Blog、BBS或个人站等:
普通尺寸(450*500pix)
较大尺寸(630*500pix)
你可能喜欢JavaMail异步邮件发送 - 50% off - ITeye技术网站
博客分类:
今天把之前写的使用JavaMail异步发送邮件的demo程序贴出来。
最近一段时间,发现新浪微博手机客户端也开始支持异步发送信息了。不管是发微博,还是评论微博,点击过“发送”按钮之后,马上会被告知“已经进入发送队列”,我觉得这明显增加了用户体验,并且这个提升也不存在任何技术困难。这样一种情况,比如我发一个带图的微博消息,在不使用wifi的情况下,上传一个稍大些的图片可能会耗费不少时间。假如微博客户端不支持异步发送,也许就因为图片的上传,这个客户端得卡上好半天,直到上传完成为止。这种完全阻塞的方式,对用户来说可不是种好的体验。
发送邮件的时候同样存在着类似上面的情况。整个邮件的发送过程是比较耗时的,假如使用普通的单线程串行处理方式,当并发量大时,必然带来灾难性的后果。在下面的例子中,我使用多线程的方式来解决这个问题,使得邮件支持异步发送。
要支持新浪微博的异步发送,可以使用多线程方式,也可以使用消息服务。我本身对于JMS的方式不太了解,因此选择了一种相对熟悉和容易实现的方式,即每个邮件发送请求都作为一个线程任务,由线程池中的线程来处理每一个邮件发送任务。
首先,介绍邮件的JavaBean对象Mail。很简单,无需赘言。
package org.tang.financial.
import java.util.L
public class Mail {
private List&String& recipientsTo;
private List&String& recipientsCc;
private List&String& recipientsB
* 附件列表
private List&String&
public String getSender() {
public void setSender(String sender) {
this.sender =
public List&String& getRecipientsTo() {
return recipientsTo;
public void setRecipientsTo(List&String& recipientsTo) {
this.recipientsTo = recipientsTo;
public List&String& getRecipientsCc() {
return recipientsCc;
public void setRecipientsCc(List&String& recipientsCc) {
this.recipientsCc = recipientsCc;
public List&String& getRecipientsBcc() {
return recipientsB
public void setRecipientsBcc(List&String& recipientsBcc) {
this.recipientsBcc = recipientsB
public String getSubject() {
public void setSubject(String subject) {
this.subject =
public String getBody() {
public void setBody(String body) {
this.body =
public List&String& getAttachments() {
public void setAttachments(List&String& attachments) {
this.attachments =
其次,是邮件发送程序当中需要用到的常量。各个常量的含义都已经有说明,也无需赘言。
package org.tang.financial.
public abstract class MailProperties {
* SMTP服务器
public static final String MAIL_SMTP_HOST = "mail.smtp.host";
* SMTP服务器端口号
public static final String MAIL_SMTP_PORT = "mail.smtp.port";
* 登录SMTP服务器是否需要通过授权。可选值为true和false
public static final String MAIL_SMTP_AUTH = "mail.smtp.auth";
* 登录SMTP服务器默认邮箱账号
public static final String MAIL_SMTP_USER = "mail.smtp.user";
* 登录SMTP服务器默认邮箱账号对应密码
public static final String MAIL_SMTP_PASSWORD = "mail.smtp.password";
* 是否打开程序调试。可选值包括true和false
public static final String MAIL_DEBUG = "mail.debug";
接着,是邮件发送程序需要使用到得properties属性配置文件。各个键值的含义参考上面的说明。
mail.smtp.host =
mail.smtp.port = 25
mail.smtp.auth = true
mail.smtp.user =
mail.smtp.password = password
mail.debug = true
最后,邮件发送的处理程序。
package org.tang.financial.
import java.io.IOE
import java.io.InputS
import java.util.D
import java.util.L
import java.util.P
import java.util.concurrent.E
import java.util.concurrent.E
import javax.mail.A
import javax.mail.M
import javax.mail.MessagingE
import javax.mail.M
import javax.mail.PasswordA
import javax.mail.S
import javax.mail.T
import javax.mail.internet.AddressE
import javax.mail.internet.InternetA
import javax.mail.internet.MimeBodyP
import javax.mail.internet.MimeM
import javax.mail.internet.MimeM
import mons.logging.L
import mons.logging.LogF
import org.
import org.tang.financial.domain.M
import org.tang.financial.mail.MailP
import org.tang.financial.util.CollectionU
import org.tang.financial.util.StringU
@Component
public class MailService {
private static Log logger = LogFactory.getLog(MailService.class);
private static final String MAIL_PROPERTIE_NAME = "JavaMail.properties";
private static Properties mailPro = new Properties();
private static Executor executor = Executors.newFixedThreadPool(10);
//初始化,读取属性文件的过程
InputStream in =
in = MailService.class.getResourceAsStream(MAIL_PROPERTIE_NAME);
mailPro.load(in);
} catch (IOException e) {
if (logger.isErrorEnabled()) {
logger.error(e);
} finally {
if (in != null) {
in.close();
} catch (IOException e) {
if (logger.isErrorEnabled()) {
logger.error(e);
public boolean sendMail(final Mail mail) {
if(mail == null){
//创建邮件发送任务
Runnable task = new Runnable() {
public void run() {
final String username = mailPro.getProperty(MailProperties.MAIL_SMTP_USER);
final String password = mailPro.getProperty(MailProperties.MAIL_SMTP_PASSWORD);
//创建发送邮件的会话
Session session = Session.getDefaultInstance(mailPro, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
//创建邮件消息
MimeMessage msg = new MimeMessage(session);
//设置邮件发送人
msg.setFrom(new InternetAddress(StringUtils.isEmpty(mail
.getSender()) ? mailPro
.getProperty(MailProperties.MAIL_SMTP_USER) : mail
.getSender()));
//分别设置邮件的收件人、抄送人和密送人
msg.setRecipients(Message.RecipientType.TO, strListToInternetAddresses(mail.getRecipientsTo()));
msg.setRecipients(Message.RecipientType.CC, strListToInternetAddresses(mail.getRecipientsCc()));
msg.setRecipients(Message.RecipientType.BCC, strListToInternetAddresses(mail.getRecipientsBcc()));
//设置邮件主题
msg.setSubject(mail.getSubject());
Multipart mp = new MimeMultipart();
//创建邮件主体内容
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(mail.getBody());
mp.addBodyPart(mbp1);
if(!CollectionUtils.isEmpty(mail.getAttachments())){
//循环添加邮件附件
MimeBodyPart attach =
for(String path : mail.getAttachments()){
attach = new MimeBodyPart();
attach.attachFile(path);
mp.addBodyPart(attach);
} catch (IOException e) {
if (logger.isErrorEnabled()) {
logger.error(e);
msg.setContent(mp);
msg.setSentDate(new Date());
//邮件开始发送
Transport.send(msg);
} catch (AddressException e) {
if (logger.isErrorEnabled()) {
logger.error(e);
} catch (MessagingException e) {
if (logger.isErrorEnabled()) {
logger.error(e);
//使用Executor框架的线程池执行邮件发送任务
executor.execute(task);
* 将列表中的字符串转换成InternetAddress对象
* @param list 邮件字符串地址列表
* @return InternetAddress对象数组
private InternetAddress[] strListToInternetAddresses(List&String& list) {
if (list == null || list.isEmpty()) {
int size = list.size();
InternetAddress[] arr = new InternetAddress[size];
for (int i = 0; i & i++) {
arr[i] = new InternetAddress(list.get(i));
} catch (AddressException e) {
e.printStackTrace();
ssy341 写道没看出哪里异步了
要不你再去翻翻书?
你是使用了线程 ,像三楼说的那样?
没看出哪里异步了要不你再去翻翻书?
Will_Turner
浏览: 25107 次
来自: 杭州
受教了!!
printList(destList);
srcList.g ...
CollectionUtils 也放出来嘛
Will_Turner,StringUtils也放出来嘛,猜来 ...
非常不过,很感谢Will_Turner无私奉献 !}

我要回帖

更多关于 javamail qq企业邮箱 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信