Java Mail 发送多人、抄送多人,附件上传 邮件发送功能

package com.tobacco.ermsuite.interfaces.mail;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class MailAuthenticator extends Authenticator {
String userName = null;
String password = null;

public MailAuthenticator() {
}

public MailAuthenticator(String username, String password) {
this.userName = username;
this.password = password;
}

protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}

}

package com.tobacco.ermsuite.interfaces.mail;

 

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

public class MailFactory {

private static MailProperties defaultProp;

static {

defaultProp = new MailProperties();

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

defaultProp.setMailServerPort("25");

defaultProp.setValidate(true);

defaultProp.setUserName("oops22");

defaultProp.setPassword("wen789789");// 您的邮箱密码

}

 

public static Map sendMail(String subject, String content, List toAddress,

List ccAddress,Map attachFile) {

Map resultMap = new HashMap();

if (toAddress != null && toAddress.size() > 0) {

defaultProp.setToAddress(toAddress);

defaultProp.setCcAddress(ccAddress);

defaultProp.setAttachFile(attachFile);

defaultProp.setSubject(subject);

defaultProp.setContent(content);

resultMap = MailUtil.sendHtmlMail(defaultProp);

} else {

resultMap.put("state", "failed");

resultMap.put("message", "邮件发送失败!错误原因:收件人为空");

}

 

return resultMap;

}

 

public static Map sendMail(String subject, String content, List toAddress,Map attachFile) {

Map resultMap = sendMail(subject, content, toAddress, null,attachFile);

return resultMap;

}

 

}

 

package com.tobacco.ermsuite.interfaces.mail;

 

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.Properties;

 

public class MailProperties {

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

private String mailServerHost;

private String mailServerPort = "25";

// 邮件发送者的地址

private String fromAddress;

// 邮件接收者的地址

private List toAddress;

// 抄送的地址

private List ccAddress;

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

private String userName;

private String password;

// 是否需要身份验证

private boolean validate = false;

// 邮件主题

private String subject = "";

// 邮件的文本内容

private String content = "";

// 邮件附件

private Map attachFile;

// 邮件附件的文件名

private List attachFileNames;

 

/**

* 获得邮件会话属性

*/

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 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 List getAttachFileNames() {

return attachFileNames;

}

 

public void setAttachFileNames(List fileNames) {

this.attachFileNames = fileNames;

}

 

public void addAttachFileNames(String fileNames) {

if (attachFileNames == null) {

this.attachFileNames = new ArrayList();

}

this.attachFileNames.add(fileNames);

}

 

public Map getAttachFile() {

return attachFile;

}

 

public void setAttachFile(Map attachFile) {

if (attachFile == null) {

this.attachFile = new HashMap();

}

this.attachFile = attachFile;

}

 

public String getFromAddress() {

String fromAdd = "";

if (fromAddress != null && fromAddress != "") {

fromAdd = fromAddress;

} else {

fromAdd = userName.split("@")[0]

+ "@"

+ mailServerHost.substring(mailServerHost.indexOf(".") + 1,

mailServerHost.length());

 

}

return fromAdd;

}

 

public void setFromAddress(String fromAddress) {

this.fromAddress = fromAddress;

}

 

public String getPassword() {

return password;

}

 

public void setPassword(String password) {

this.password = password;

}

 

public List getToAddress() {

return toAddress;

}

 

public void addToAddress(String toAddress) {

if (toAddress == null) {

this.toAddress = new ArrayList();

}

this.toAddress.add(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 List getCcAddress() {

return ccAddress;

}

 

public void addCcAddress(String ccAddress) {

if (ccAddress == null) {

this.ccAddress = new ArrayList();

}

this.ccAddress.add(ccAddress);

}

 

public void setToAddress(List toAddress) {

this.toAddress = toAddress;

}

 

public void setCcAddress(List ccAddress) {

this.ccAddress = ccAddress;

}

}

 

package com.tobacco.ermsuite.interfaces.mail;

 

import java.io.UnsupportedEncodingException;

import java.util.Date;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import java.util.Properties;

 

import javax.activation.DataHandler;

import javax.mail.Address;

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.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 javax.mail.util.ByteArrayDataSource;

 

public class MailUtil {

/**

* 以HTML格式发送邮件

* @param mailInfo

*            待发送的邮件信息

*/

public synchronized static Map sendHtmlMail(MailProperties mailPro) {

Map resultMap = new HashMap();

resultMap.put("state", "success");

String message = "邮件发送成功!";

// 判断是否需要身份认证

MailAuthenticator authenticator = null;

Properties pro = mailPro.getProperties();

// 如果需要身份认证,则创建一个密码验证器

if (mailPro.isValidate()) {

authenticator = new MailAuthenticator(mailPro.getUserName(),

mailPro.getPassword());

}

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

Session sendMailSession = Session

.getDefaultInstance(pro, authenticator);

try {

// 根据session创建一个邮件消息

MimeMessage mailMessage = new MimeMessage(sendMailSession);

// 创建邮件发送者地址

Address from = new InternetAddress(mailPro.getFromAddress());

// 设置邮件消息的发送者

mailMessage.setFrom(from);

// 创建邮件的接收者地址,并设置到邮件消息中

List to = mailPro.getToAddress();

List cc = mailPro.getCcAddress();

mailMessage.setRecipients(Message.RecipientType.TO,

listToAddressArray(to));

if (cc != null) {

mailMessage.setRecipients(Message.RecipientType.CC,

listToAddressArray(cc));

}

 

// 设置邮件消息的主题

mailMessage.setSubject(mailPro.getSubject());

// 设置邮件消息发送的时间

mailMessage.setSentDate(new Date());

// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象

Multipart mainPart = new MimeMultipart();

// 创建一个包含HTML内容的MimeBodyPart

BodyPart html = new MimeBodyPart();

// 设置HTML内容

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

mainPart.addBodyPart(html);

 

// 附件上传

Map attachFile = mailPro.getAttachFile();

if (attachFile != null) {

Iterator it = attachFile.entrySet().iterator();

while (it.hasNext()) {

MimeBodyPart mbp = new MimeBodyPart();

Map.Entry entry = (Map.Entry) it.next();

mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(

(byte[]) entry.getValue(),

"application/octet-stream")));

try {

mbp.setFileName(MimeUtility.encodeText(String

.valueOf(entry.getKey())));

} catch (UnsupportedEncodingException e) {

// TODO Auto-generated catch block

message = "邮件发送失败!错误原因:附件名称解析出错\n";

resultMap.put("state", "failed");

e.printStackTrace();

}

mainPart.addBodyPart(mbp);

}

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

// MimeBodyPart mbp=new MimeBodyPart();

// FileDataSource source = new

// FileDataSource("E:\\FTP\\你好.java");

// mbp.setDataHandler(new DataHandler(source));

// mbp.setDataHandler(new DataHandler(new

// ByteArrayDataSource((byte[])attachFile.get(i),"application/octet-stream")));

// try {

// mbp.setFileName(MimeUtility.encodeText("211111"));

// } catch (UnsupportedEncodingException e) {

// // TODO Auto-generated catch block

// message="邮件发送失败!错误原因:附件名称解析出错\n";

// resultMap.put("state", "failed");

// e.printStackTrace();

// }

// mainPart.addBodyPart(mbp);

// }

}

 

// 将MiniMultipart对象设置为邮件内容

mailMessage.setContent(mainPart);

// 发送邮件

Transport.send(mailMessage);

 

} catch (MessagingException ex) {

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

resultMap.put("state", "failed");

ex.printStackTrace();

}

resultMap.put("message", message);

return resultMap;

}

 

private static Address[] listToAddressArray(List list) {

Address[] array = new Address[list.size()];

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

String str = String.valueOf(list.get(i));

Address address = null;

try {

address = new InternetAddress(str);

} catch (AddressException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

array[i] = address;

}

return array;

 

}

}

 

 

package com.tobacco.ermsuite.interfaces.util;

 

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

import org.apache.axis.client.Call;

import org.apache.axis.client.Service;

 

import com.tobacco.ermsuite.interfaces.mail.MailFactory;

 

public class TestWebService extends Thread {

 

public static void main(String[] args) {

 

 

List toAddress = new ArrayList();

List ccAddress = new ArrayList();

Map map = new HashMap();

map.put("你好.docx", readToByte("E:\\项目资料\\浙江项目\\SVN\\3.设计阶段\\3.1概要设计\\01浙江烟草商业物流管控信息系统概要设计报告(省局报表).docx"));

toAddress.add("[email protected]");

ccAddress.add("[email protected]");

String subject = "测试上传流附件";

String content = "<B>你好吗!清单</B>";

 

Map resmap = MailFactory.sendMail(subject, content, toAddress,map);

System.out.println(resmap.get("message"));

 

}

 

public static byte[] readToByte(String fileName) {

File file = new File(fileName);

Long filelength = file.length();

byte[] filecontent = new byte[filelength.intValue()];

try {

FileInputStream in = new FileInputStream(file);

in.read(filecontent);

in.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return filecontent;

 

}

 

}

 

 

你可能感兴趣的:(java)