java 多线程发送邮件_Java实现多线程邮件发送

利用java多线程技术配合线程池实现多任务邮件发送.

1.基本邮件发送MailSender

packagehk.buttonwood.ops.email;importjava.io.File;importjava.util.Date;importjava.util.Enumeration;importjava.util.Properties;importjava.util.Vector;importjavax.activation.DataHandler;importjavax.activation.FileDataSource;importjavax.mail.Address;importjavax.mail.AuthenticationFailedException;importjavax.mail.BodyPart;importjavax.mail.Message;importjavax.mail.MessagingException;importjavax.mail.Multipart;importjavax.mail.Session;importjavax.mail.Transport;importjavax.mail.internet.InternetAddress;importjavax.mail.internet.MimeBodyPart;importjavax.mail.internet.MimeMessage;importjavax.mail.internet.MimeMultipart;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;/*** 简单邮件(带附件的邮件)发送器*/

public classMailSender {private Logger logger = LoggerFactory.getLogger(MailSender.class);public static voidmain(String[] args) {//这个类主要是设置邮件

MailSenderInfo mailInfo = newMailSenderInfo();

mailInfo.setMailServerHost("smtp.163.com");

mailInfo.setMailServerPort("25");

mailInfo.setValidate(true);

mailInfo.setUserName("15138666597");

mailInfo.setPassword("myb1991517");//您的邮箱密码

mailInfo.setFromAddress("15138666597@163.com");

mailInfo.setToAddress("930147677@qq.com");

mailInfo.setSubject("windowfg");

mailInfo.setContent("asgjhkhl");//这个类主要来发送邮件

MailSender sms = newMailSender();

Vector files = new Vector();

files.addElement(new File("/home/maybo/myProject/2015-11-04/mt_2015-11-04_2.pdf"));

mailInfo.setFile(files);

sms.sendWithAttachment(mailInfo);//发送文体格式//sms.sendHtmlMail(mailInfo);//发送html格式

}/*** 发送邮件*/

publicMailState sendWithAttachment(MailSenderInfo info) {

MailState mailState=newMailState();

mailState.setDate(info.getDate());

mailState.setState(MailState.SUCCESS);

mailState.setDesc("邮箱发送成功!");

mailState.setAddress(info.getToAddress());

Session session= null;

Properties props=System.getProperties();

props.put("mail.smtp.host", info.getMailServerHost());if (info.isValidate()) { //服务器需要身份认证

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

MyAuthenticator smtpAuth= newMyAuthenticator(info.getUserName(), info.getPassword());

session=Session.getDefaultInstance(props, smtpAuth);

}else{

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

session= Session.getDefaultInstance(props, null);

}//session.setDebug(true);

Transport trans = null;try{

Message msg= newMimeMessage(session);try{

Address from_address= newInternetAddress(info.getFromAddress(), info.getUserName());

msg.setFrom(from_address);

}catch(java.io.UnsupportedEncodingException e) {//e.printStackTrace();

mailState.setState(MailState.ERROR);

String message= "邮件发送失败!";

mailState.setDesc(message);

}

InternetAddress[] address= { newInternetAddress(info.getToAddress()) };

msg.setRecipients(Message.RecipientType.TO, address);

msg.setSubject(info.getSubject());

Multipart mp= newMimeMultipart();

MimeBodyPart mbp= newMimeBodyPart();

mbp.setContent(info.getContent().toString(),"text/html;charset=gb2312");

mp.addBodyPart(mbp);if (!info.getFile().isEmpty()) {//有附件

Enumeration> efile =info.getFile().elements();while(efile.hasMoreElements()) {

mbp= newMimeBodyPart();

String filename= efile.nextElement().toString(); //选择出每一个附件名

FileDataSource fds = new FileDataSource(filename); //得到数据源

mbp.setDataHandler(new DataHandler(fds)); //得到附件本身并至入BodyPart

mbp.setFileName(fds.getName()); //得到文件名同样至入BodyPart

mp.addBodyPart(mbp);

}

info.getFile().removeAllElements();

}

msg.setContent(mp);//Multipart加入到信件

msg.setSentDate(new Date()); //设置信件头的发送日期//发送信件

msg.saveChanges();

trans= session.getTransport("smtp");

trans.connect(info.getMailServerHost(), info.getUserName(), info.getPassword());

trans.sendMessage(msg, msg.getAllRecipients());

trans.close();

}catch(AuthenticationFailedException e) {

mailState.setState(MailState.ERROR);

String message= "邮件发送失败!错误原因:\n" + "身份验证错误!";

mailState.setDesc(message);//e.printStackTrace();

} catch(MessagingException e) {//e.printStackTrace();

String message = "邮件发送失败!错误原因:" +e.getMessage();

mailState.setDesc(message);

mailState.setState(MailState.ERROR);

}returnmailState;

}/*** 以文本格式发送邮件

*

*@parammailInfo

* 待发送的邮件的信息*/

public booleansendTextMail(MailSenderInfo mailInfo) {//判断是否需要身份认证

MyAuthenticator authenticator = null;

Properties pro=mailInfo.getProperties();if(mailInfo.isValidate()) {//如果需要身份认证,则创建一个密码验证器

authenticator = newMyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());

}//根据邮件会话属性和密码验证器构造一个发送邮件的session

Session sendMailSession =Session.getDefaultInstance(pro, authenticator);try{//根据session创建一个邮件消息

Message mailMessage = newMimeMessage(sendMailSession);//创建邮件发送者地址

Address from = newInternetAddress(mailInfo.getFromAddress());//设置邮件消息的发送者

mailMessage.setFrom(from);//创建邮件的接收者地址,并设置到邮件消息中

Address to = newInternetAddress(mailInfo.getToAddress());

mailMessage.setRecipient(Message.RecipientType.TO, to);//设置邮件消息的主题

mailMessage.setSubject(mailInfo.getSubject());//设置邮件消息发送的时间

mailMessage.setSentDate(newDate());//设置邮件消息的主要内容

String mailContent =mailInfo.getContent();

mailMessage.setText(mailContent);//发送邮件

Transport.send(mailMessage);return true;

}catch(MessagingException ex) {

ex.printStackTrace();

}return false;

}/*** 以HTML格式发送邮件

*

*@parammailInfo

* 待发送的邮件信息*/

public static booleansendHtmlMail(MailSenderInfo mailInfo) {//判断是否需要身份认证

MyAuthenticator authenticator = null;

Properties pro=mailInfo.getProperties();//如果需要身份认证,则创建一个密码验证器

if(mailInfo.isValidate()) {

authenticator= newMyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());

}//根据邮件会话属性和密码验证器构造一个发送邮件的session

Session sendMailSession =Session.getDefaultInstance(pro, authenticator);try{//根据session创建一个邮件消息

Message mailMessage = newMimeMessage(sendMailSession);//创建邮件发送者地址

Address from = newInternetAddress(mailInfo.getFromAddress());//设置邮件消息的发送者

mailMessage.setFrom(from);//创建邮件的接收者地址,并设置到邮件消息中

Address to = newInternetAddress(mailInfo.getToAddress());//Message.RecipientType.TO属性表示接收者的类型为TO

mailMessage.setRecipient(Message.RecipientType.TO, to);//设置邮件消息的主题

mailMessage.setSubject(mailInfo.getSubject());//设置邮件消息发送的时间

mailMessage.setSentDate(newDate());//MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象

Multipart mainPart = newMimeMultipart();//创建一个包含HTML内容的MimeBodyPart

BodyPart html = newMimeBodyPart();//设置HTML内容

html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");

mainPart.addBodyPart(html);//将MiniMultipart对象设置为邮件内容

mailMessage.setContent(mainPart);//发送邮件

Transport.send(mailMessage);return true;

}catch(MessagingException ex) {

ex.printStackTrace();

}return false;

}

}

2.邮件发送信息MailSenderInfo

package hk.buttonwood.ops.email;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.Serializable;

import java.util.Arrays;

import java.util.Properties;

import java.util.Vector;

public class MailSenderInfo implements Serializable {

// 发送邮件的服务器的IP和端口

private String mailServerHost;

private String mailServerPort = "25";

private long uid;//唯一标示

// 邮件发送者的地址

private String fromAddress;

// 邮件接收者的地址

private String toAddress;

// 登陆邮件发送服务器的用户名和密码

private String userName;

private String password;

// 是否需要身份验证

private boolean validate = false;

// 邮件主题

private String filename="";

private Vector file = new Vector(); //用于保存发送附件的文件名的集合

private String subject;

// 邮件的文本内容

private String content;

// 邮件附件的文件名

private String[] attachFileNames;

//邮箱来源

private int portfolio;

//邮箱来源日期

private String date;

public void setUid(long uid) {

this.uid = uid;

}

public long getUid() {

return uid;

}

public void setDate(String date) {

this.date = date;

}

public void setPortfolio(int portfolio) {

this.portfolio = portfolio;

}

public String getDate() {

return this.date;

}

public int getPortfolio() {

return this.portfolio;

}

/**

* 获得邮件会话属性

*/

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");

return p;

}

public String getMailServerHost() {

return mailServerHost;

}

public void setFile(Vector file) {

this.file = file;

}

public Vector getFile() {

return this.file;

}

public void setFilename(String filename) {

this.filename = filename;

}

public String getFilename() {

return this.filename;

}

public void setMailServerHost(String mailServerHost) {

this.mailServerHost = mailServerHost;

}

public String getMailServerPort() {

return mailServerPort;

}

public void setMailServerPort(String mailServerPort) {

this.mailServerPort = mailServerPort;

}

public boolean isValidate() {

return validate;

}

public void setValidate(boolean validate) {

this.validate = validate;

}

public String[] getAttachFileNames() {

return attachFileNames;

}

public void setAttachFileNames(String[] fileNames) {

this.attachFileNames = fileNames;

}

public String getFromAddress() {

return fromAddress;

}

public void setFromAddress(String fromAddress) {

this.fromAddress = fromAddress;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public String getToAddress() {

return toAddress;

}

public void setToAddress(String toAddress) {

this.toAddress = toAddress;

}

public String getUserName() {

return userName;

}

public void setUserName(String userName) {

this.userName = userName;

}

public String getSubject() {

return subject;

}

public void setSubject(String subject) {

this.subject = subject;

}

public String getContent() {

return content;

}

public void setContent(String textContent) {

this.content = textContent;

}

public Object deepCopy() throws Exception

{

// 将该对象序列化成流,因为写在流里的是对象的一个拷贝,而原对象仍然存在于JVM里面。所以利用这个特性可以实现对象的深拷贝

ByteArrayOutputStream bos = new ByteArrayOutputStream();

ObjectOutputStream oos = new ObjectOutputStream(bos);

oos.writeObject(this);

// 将流序列化成对象

ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());

ObjectInputStream ois = new ObjectInputStream(bis);

return ois.readObject();

}

@Override

public String toString() {

return "MailSenderInfo [mailServerHost=" + this.mailServerHost + ", mailServerPort=" + this.mailServerPort

+ ", fromAddress=" + this.fromAddress + ", toAddress=" + this.toAddress + ", userName=" + this.userName

+ ", password=" + this.password + ", validate=" + this.validate + ", filename=" + this.filename

+ ", file=" + this.file + ", subject=" + this.subject + ", content=" + this.content

+ ", attachFileNames=" + Arrays.toString(this.attachFileNames) + ", portfolio=" + this.portfolio

+ ", date=" + this.date + "]";

}

}

3.权限MyAuthenticator

package hk.buttonwood.ops.email;

import javax.mail.Authenticator;

import javax.mail.PasswordAuthentication;

public class MyAuthenticator extends Authenticator {

String userName = null;

String password = null;

public MyAuthenticator() {

}

public MyAuthenticator(String username, String password) {

this.userName = username;

this.password = password;

}

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(userName, password);

}

}

4.创建一个发送邮件的线程任务

package hk.buttonwood.ops.email;

import java.util.concurrent.LinkedBlockingQueue;

import hk.buttonwood.ops.email.MailState;

/**

* @author maybo 2015年11月4日

*/

public class MailSendTask extends Thread {

private LinkedBlockingQueue msgs;// 非阻塞线程安全队列用于存储发送的消息

public void setMsgs(LinkedBlockingQueue msgs) {

this.msgs = msgs;

}

private MailSenderInfo mailSenderInfo;

public void setMailSenderInfo(MailSenderInfo mailSenderInfo) {

this.mailSenderInfo = mailSenderInfo;

}

/*

* @param:发送的消息状态

*

* @param:发送信息

*/

public MailSendTask(LinkedBlockingQueue msgs, MailSenderInfo mailSenderInfo) {

this.msgs = msgs;

this.mailSenderInfo = mailSenderInfo;

}

@Override

public void run() {

MailSender mailSender = new MailSender();

MailState mailState = mailSender.sendWithAttachment(mailSenderInfo);

msgs.add(mailState);

}

}

5.邮件发送服务

package hk.buttonwood.ops.email;

import java.io.File;

import java.util.List;

import java.util.Vector;

import java.util.concurrent.LinkedBlockingQueue;

import javax.annotation.Resource;

import hk.buttonwood.ops.report.BaseReportConf;

import net.zweb.core.util.FileUtil;

/**

* @author maybo 2015年11月4日

*/

@Resource

public class MailSendService extends BaseReportConf {

public LinkedBlockingQueue msgs;

public MailSenderOperation mailSenderOperation;

private ReportSendInfo info = null;

public MailSendService() {

mailSenderOperation = new MailSenderOperation();

msgs = new LinkedBlockingQueue();

mailSenderOperation.excute(msgs);

info = ReportSendInfo.instance();

}

public void send(List toAddress, String reportType, String date,String date2, int portfolio, String root, long uid)

throws Exception {

MailState mailState = new MailState();

mailState.setPorftolio(portfolio);

mailState.setUid(uid);

if (toAddress == null) {

mailState.setDate(date);

mailState.setDate(date);

mailState.setState(MailState.NOT_ADDRESS);

mailState.setDesc("没有相应发送地址!");

msgs.add(mailState);

return;

}

File file = obtainFile(date,date2, reportType, portfolio, root);

if (file != null) {

MailSenderInfo mInfo = info.create(reportType);

Vector vectors = new Vector();

vectors.addElement(file);

mInfo.setFile(vectors);

for (int i = 0; i < toAddress.size(); i++) {

MailSenderInfo senderInfo = new MailSenderInfo();

senderInfo = cpSendInfo(mInfo);

senderInfo.setToAddress(toAddress.get(i));

senderInfo.setPortfolio(portfolio);

senderInfo.setDate(date);

senderInfo.setUid(uid);

mailSenderOperation.addTask(senderInfo);

}

} else {

mailState.setPorftolio(portfolio);

mailState.setUid(uid);

mailState.setDate(date);

mailState.setState(MailState.NOT_EXIST);

mailState.setDesc("发送的报表没有生成!");

msgs.add(mailState);

}

}

private MailSenderInfo cpSendInfo(MailSenderInfo info) {

MailSenderInfo senderInfo = new MailSenderInfo();

senderInfo.setAttachFileNames(info.getAttachFileNames());

senderInfo.setContent(info.getContent());

senderInfo.setFile(info.getFile());

senderInfo.setFilename(info.getFilename());

senderInfo.setFromAddress(info.getFromAddress());

senderInfo.setMailServerHost(info.getMailServerHost());

senderInfo.setMailServerPort(info.getMailServerPort());

senderInfo.setPassword(info.getPassword());

senderInfo.setSubject(info.getSubject());

senderInfo.setToAddress(info.getToAddress());

senderInfo.setUserName(info.getUserName());

senderInfo.setValidate(info.isValidate());

return senderInfo;

}

/*

* 通过日期,报告类型,以及投资组合获取对应的pdf

*/

private File obtainFile(String date,String date2, String reportType, int portfolio, String root) {

String path = null;

if(date2==null||date2==""){

path = root + "/" + reportType + "_" + date + "_" + portfolio + ".pdf";

}else{

path = root + "/" + reportType + "_" + date+"_"+date2 + "_" + portfolio + ".pdf";

}

if (!FileUtil.exists(path)) {

return null;

} else {

File file = new File(path);

return file;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 以下是一个简单的 Java 多线程发送邮件的示例代码: ```java import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class SendEmail implements Runnable { private String to; private String subject; private String body; private String from; private String password; public SendEmail(String to, String subject, String body, String from, String password) { this.to = to; this.subject = subject; this.body = body; this.from = from; this.password = password; } public void run() { String host = "smtp.gmail.com"; Properties props = new Properties(); props.put("mail.smtp.host", host); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.port", "587"); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject(subject); message.setText(body); Transport.send(message); System.out.println("Sent email to " + to); } catch (MessagingException e) { throw new RuntimeException(e); } } public static void main(String[] args) { String from = "your.email@gmail.com"; String password = "your.password"; String to1 = "recipient1@example.com"; String to2 = "recipient2@example.com"; String subject = "Testing"; String body = "This is a test email."; Thread t1 = new Thread(new SendEmail(to1, subject, body, from, password)); Thread t2 = new Thread(new SendEmail(to2, subject, body, from, password)); t1.start(); t2.start(); } } ``` 该示例使用 JavaMail API 和 Gmail SMTP 服务器来发送电子邮件。您需要将 `from` 和 `password` 变量设置为您自己的电子邮件地址和密码,并将 `to1` 和 `to2` 变量设置为您想要发送邮件的收件人地址。在 `main` 方法中,我们创建了两个线程来发送邮件,每个线程负责向一个收件人发送邮件。 ### 回答2: Java多线程发送邮件实现可以通过使用Java Mail API来完成。 首先,需要导入Java Mail API相关的jar包,比如javax.mail.jar和javax.mail-api.jar。 然后,创建一个实现了Runnable接口的线程类,例如SendEmailRunnable。在run方法中,可以编写发送邮件的逻辑。可以使用Java Mail提供的API来建立邮件会话、创建邮件消息、设置收件人、主题、正文等信息,并最终发送。 在主线程中,可以创建多个SendEmailRunnable对象,并使用Thread类来启动这些线程。这样可以同时发送多封邮件,提高发送效率。 下面是一个简单示例: import java.util.Properties; import javax.mail.*; import javax.mail.internet.*; public class SendEmailRunnable implements Runnable { private String toEmail; private String subject; private String content; public SendEmailRunnable(String toEmail, String subject, String content) { this.toEmail = toEmail; this.subject = subject; this.content = content; } @Override public void run() { // 设置SMTP服务器 Properties props = new Properties(); props.setProperty("mail.smtp.host", "smtp.example.com"); props.setProperty("mail.smtp.auth", "true"); // 创建邮件会话 Session session = Session.getDefaultInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("username", "password"); } }); try { // 创建邮件消息 MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress("from@example.com")); message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail)); message.setSubject(subject); message.setText(content); // 发送邮件 Transport.send(message); System.out.println("邮件发送成功!"); } catch (Exception e) { e.printStackTrace(); } } } 然后,可以在主线程中创建多个SendEmailRunnable对象,并使用Thread类来启动这些线程,例如: public class Main { public static void main(String[] args) { SendEmailRunnable email1 = new SendEmailRunnable("email1@example.com", "主题1", "内容1"); SendEmailRunnable email2 = new SendEmailRunnable("email2@example.com", "主题2", "内容2"); new Thread(email1).start(); new Thread(email2).start(); } } 通过多线程发送邮件可以同时处理多个邮件发送请求,提高发送效率和响应速度。但需要注意邮件服务器的性能和限制,避免过多的邮件发送导致服务器拒绝服务或被视为垃圾邮件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值