Java 发送邮件(多接收者和多附件)
//实体类:
//发送邮件程序
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
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;
public class SendMail {
public boolean Send(MailInfo mailInfo)throws Exception{
Properties props=new Properties();
//设置发送邮件的邮件服务器的属性(这里使用网易的smtp服务器)
props.put("mail.smtp.host", mailInfo.getHost());
//需要经过授权,也就是有户名和密码的校验,这样才能通过验证(一定要有这一条)
props.put("mail.smtp.auth", mailInfo.getValidate());
Session session=Session.getDefaultInstance(props);// 用刚刚设置好的props对象构建一个session
// session.setDebug(true);
MimeMessage message=new MimeMessage(session);
try{
message.setFrom(new InternetAddress(mailInfo.getFromAddress()));
InternetAddress[] sendTo = new InternetAddress[mailInfo.getSendAddress().length];
for(int i=0;i<mailInfo.getSendAddress().length;i++){
sendTo[i]=new InternetAddress(mailInfo.getSendAddress()[i]);
}
// message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailInfo.getToAddress()));
message.setRecipients(Message.RecipientType.TO, sendTo);
message.setSubject(mailInfo.getSubject());
message.setSentDate(mailInfo.getSentdate());
//向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
Multipart multipart=new MimeMultipart();
BodyPart contentPart=new MimeBodyPart();
contentPart.setText(mailInfo.getContent());
multipart.addBodyPart(contentPart);
//添加附件
for(int i=0;i<mailInfo.getFilepath().length;i++){
BodyPart messageBodyPart=new MimeBodyPart();
String fpath=mailInfo.getFilepath()[i].split(",")[0];
DataSource source=new FileDataSource(fpath);
messageBodyPart.setDataHandler(new DataHandler(source));
sun.misc.BASE64Encoder enc=new sun.misc.BASE64Encoder();
String lname=fpath.substring(fpath.lastIndexOf("."), fpath.length());
String fname=String.valueOf(System.currentTimeMillis())+lname;
messageBodyPart.setFileName("=?GBK?B?"+enc.encode(fname.getBytes())+"?=");
multipart.addBodyPart(messageBodyPart);
}
message.setContent(multipart);//text/plain表示纯文本内容
message.saveChanges();
Transport transport=session.getTransport("smtp");
transport.connect(mailInfo.getHost(),mailInfo.getUsername(),mailInfo.getPassword());
transport.sendMessage(message,message.getAllRecipients());
transport.close();
return true;
}catch(Exception e){
e.printStackTrace();
}
return false;
}
}
//测试代码:
/**
* 发送邮件的基本信息
* @author dell
*
*/
public class MailInfo implements java.io.Serializable{
private String host;//发送邮件的主机号
private String port;//发送邮件的端口号
private String fromAddress;//发送邮件地址
private String toAddress;//接收邮件地址
private String username;//发送邮件用户的用户名
private String password;//发送邮件用户的密码
private String validate;//是否需要身份的验证:ture认证,false不认证信息
private String subject;//邮件主题
private String content;//邮件的内容,分为文本,超文本,html等形式
private String[] filepath;//发送邮件的附件的位置
private String[] sendAddress;
private String filename;//发送邮件的附件显示的名称
private String receivepath;//接收邮件的时候附件保存的路径
private java.util.Date sentdate;
private float filesize;
private java.util.Date receivedate;
private String mailauthor;//邮件作者
private boolean read;//是否读过,true读过,false没有阅读过
private boolean ExistsFile;//是否有附件true有,false没有
private boolean replysign;//是否有回执
private String messageid;//消息ID
private int mailnumber;//邮件数目,一个用户的总邮件数
public String[] getSendAddress() {
return sendAddress;
}
public void setSendAddress(String[] sendAddress) {
this.sendAddress = sendAddress;
}
public int getMailnumber() {
return mailnumber;
}
public void setMailnumber(int mailnumber) {
this.mailnumber = mailnumber;
}
public String getMessageid() {
return messageid;
}
public void setMessageid(String messageid) {
this.messageid = messageid;
}
public boolean isExistsFile() {
return ExistsFile;
}
public boolean isRead() {
return read;
}
public void setExistsFile(boolean existsFile) {
ExistsFile = existsFile;
}
public void setRead(boolean read) {
this.read = read;
}
public boolean isReplysign() {
return replysign;
}
public void setReplysign(boolean replysign) {
this.replysign = replysign;
}
public String getMailauthor() {
return mailauthor;
}
public void setMailauthor(String mailauthor) {
this.mailauthor = mailauthor;
}
public java.util.Date getReceivedate() {
return receivedate;
}
public void setReceivedate(java.util.Date receivedate) {
this.receivedate = receivedate;
}
public java.util.Date getSentdate() {
return sentdate;
}
public void setSentdate(java.util.Date sentdate) {
this.sentdate = sentdate;
}
public String[] getFilepath() {
return filepath;
}
public void setFilepath(String[] filepath) {
this.filepath = filepath;
}
public String getContent() {
return content;
}
public String getFilename() {
return filename;
}
public String getFromAddress() {
return fromAddress;
}
public String getHost() {
return host;
}
public String getPassword() {
return password;
}
public String getPort() {
return port;
}
public String getSubject() {
return subject;
}
public String getToAddress() {
return toAddress;
}
public String getUsername() {
return username;
}
public void setContent(String content) {
this.content = content;
}
public void setFilename(String filename) {
this.filename = filename;
}
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
public void setHost(String host) {
this.host = host;
}
public void setPassword(String password) {
this.password = password;
}
public void setPort(String port) {
this.port = port;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setToAddress(String toAddress) {
this.toAddress = toAddress;
}
public void setUsername(String username) {
this.username = username;
}
public String getValidate() {
return validate;
}
public void setValidate(String validate) {
this.validate = validate;
}
public String getReceivepath() {
return receivepath;
}
public void setReceivepath(String receivepath) {
this.receivepath = receivepath;
}
}
* 发送邮件的基本信息
* @author dell
*
*/
public class MailInfo implements java.io.Serializable{
private String host;//发送邮件的主机号
private String port;//发送邮件的端口号
private String fromAddress;//发送邮件地址
private String toAddress;//接收邮件地址
private String username;//发送邮件用户的用户名
private String password;//发送邮件用户的密码
private String validate;//是否需要身份的验证:ture认证,false不认证信息
private String subject;//邮件主题
private String content;//邮件的内容,分为文本,超文本,html等形式
private String[] filepath;//发送邮件的附件的位置
private String[] sendAddress;
private String filename;//发送邮件的附件显示的名称
private String receivepath;//接收邮件的时候附件保存的路径
private java.util.Date sentdate;
private float filesize;
private java.util.Date receivedate;
private String mailauthor;//邮件作者
private boolean read;//是否读过,true读过,false没有阅读过
private boolean ExistsFile;//是否有附件true有,false没有
private boolean replysign;//是否有回执
private String messageid;//消息ID
private int mailnumber;//邮件数目,一个用户的总邮件数
public String[] getSendAddress() {
return sendAddress;
}
public void setSendAddress(String[] sendAddress) {
this.sendAddress = sendAddress;
}
public int getMailnumber() {
return mailnumber;
}
public void setMailnumber(int mailnumber) {
this.mailnumber = mailnumber;
}
public String getMessageid() {
return messageid;
}
public void setMessageid(String messageid) {
this.messageid = messageid;
}
public boolean isExistsFile() {
return ExistsFile;
}
public boolean isRead() {
return read;
}
public void setExistsFile(boolean existsFile) {
ExistsFile = existsFile;
}
public void setRead(boolean read) {
this.read = read;
}
public boolean isReplysign() {
return replysign;
}
public void setReplysign(boolean replysign) {
this.replysign = replysign;
}
public String getMailauthor() {
return mailauthor;
}
public void setMailauthor(String mailauthor) {
this.mailauthor = mailauthor;
}
public java.util.Date getReceivedate() {
return receivedate;
}
public void setReceivedate(java.util.Date receivedate) {
this.receivedate = receivedate;
}
public java.util.Date getSentdate() {
return sentdate;
}
public void setSentdate(java.util.Date sentdate) {
this.sentdate = sentdate;
}
public String[] getFilepath() {
return filepath;
}
public void setFilepath(String[] filepath) {
this.filepath = filepath;
}
public String getContent() {
return content;
}
public String getFilename() {
return filename;
}
public String getFromAddress() {
return fromAddress;
}
public String getHost() {
return host;
}
public String getPassword() {
return password;
}
public String getPort() {
return port;
}
public String getSubject() {
return subject;
}
public String getToAddress() {
return toAddress;
}
public String getUsername() {
return username;
}
public void setContent(String content) {
this.content = content;
}
public void setFilename(String filename) {
this.filename = filename;
}
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
public void setHost(String host) {
this.host = host;
}
public void setPassword(String password) {
this.password = password;
}
public void setPort(String port) {
this.port = port;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setToAddress(String toAddress) {
this.toAddress = toAddress;
}
public void setUsername(String username) {
this.username = username;
}
public String getValidate() {
return validate;
}
public void setValidate(String validate) {
this.validate = validate;
}
public String getReceivepath() {
return receivepath;
}
public void setReceivepath(String receivepath) {
this.receivepath = receivepath;
}
}
//发送邮件程序
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
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;
public class SendMail {
public boolean Send(MailInfo mailInfo)throws Exception{
Properties props=new Properties();
//设置发送邮件的邮件服务器的属性(这里使用网易的smtp服务器)
props.put("mail.smtp.host", mailInfo.getHost());
//需要经过授权,也就是有户名和密码的校验,这样才能通过验证(一定要有这一条)
props.put("mail.smtp.auth", mailInfo.getValidate());
Session session=Session.getDefaultInstance(props);// 用刚刚设置好的props对象构建一个session
// session.setDebug(true);
MimeMessage message=new MimeMessage(session);
try{
message.setFrom(new InternetAddress(mailInfo.getFromAddress()));
InternetAddress[] sendTo = new InternetAddress[mailInfo.getSendAddress().length];
for(int i=0;i<mailInfo.getSendAddress().length;i++){
sendTo[i]=new InternetAddress(mailInfo.getSendAddress()[i]);
}
// message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailInfo.getToAddress()));
message.setRecipients(Message.RecipientType.TO, sendTo);
message.setSubject(mailInfo.getSubject());
message.setSentDate(mailInfo.getSentdate());
//向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
Multipart multipart=new MimeMultipart();
BodyPart contentPart=new MimeBodyPart();
contentPart.setText(mailInfo.getContent());
multipart.addBodyPart(contentPart);
//添加附件
for(int i=0;i<mailInfo.getFilepath().length;i++){
BodyPart messageBodyPart=new MimeBodyPart();
String fpath=mailInfo.getFilepath()[i].split(",")[0];
DataSource source=new FileDataSource(fpath);
messageBodyPart.setDataHandler(new DataHandler(source));
sun.misc.BASE64Encoder enc=new sun.misc.BASE64Encoder();
String lname=fpath.substring(fpath.lastIndexOf("."), fpath.length());
String fname=String.valueOf(System.currentTimeMillis())+lname;
messageBodyPart.setFileName("=?GBK?B?"+enc.encode(fname.getBytes())+"?=");
multipart.addBodyPart(messageBodyPart);
}
message.setContent(multipart);//text/plain表示纯文本内容
message.saveChanges();
Transport transport=session.getTransport("smtp");
transport.connect(mailInfo.getHost(),mailInfo.getUsername(),mailInfo.getPassword());
transport.sendMessage(message,message.getAllRecipients());
transport.close();
return true;
}catch(Exception e){
e.printStackTrace();
}
return false;
}
}
//测试代码:
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class SendTest {
@Test
public void mailTest(){
SendMail mail=new SendMail();
MailInfo mailInfo=new MailInfo();
mailInfo.setContent("邮件内容44444444444444444444");
String[] filepath=new String[]{"D:\\1317742305879.csv","D:\\zpssoa.log","E:\\Emotion\\Photo\\好寂寞好空虚.gif"};
mailInfo.setFilepath(filepath);
// mailInfo.setFilename("希望"+fname);
mailInfo.setFromAddress("[email protected]");
mailInfo.setHost("smtp.126.com");
mailInfo.setSubject("邮件主题444444444444444444444");
// mailInfo.setToAddress("[email protected]");
String[] destination=new String[]{"[email protected]","[email protected]","[email protected]"};
mailInfo.setSendAddress(destination);
mailInfo.setUsername("leeposter");
mailInfo.setValidate("true");
mailInfo.setPassword("****");
try{
boolean flag=mail.Send(mailInfo);
if(flag==true){
System.out.println("发送成功");
}else{
System.out.println("发送失败");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
import org.junit.Before;
import org.junit.Test;
public class SendTest {
@Test
public void mailTest(){
SendMail mail=new SendMail();
MailInfo mailInfo=new MailInfo();
mailInfo.setContent("邮件内容44444444444444444444");
String[] filepath=new String[]{"D:\\1317742305879.csv","D:\\zpssoa.log","E:\\Emotion\\Photo\\好寂寞好空虚.gif"};
mailInfo.setFilepath(filepath);
// mailInfo.setFilename("希望"+fname);
mailInfo.setFromAddress("[email protected]");
mailInfo.setHost("smtp.126.com");
mailInfo.setSubject("邮件主题444444444444444444444");
// mailInfo.setToAddress("[email protected]");
String[] destination=new String[]{"[email protected]","[email protected]","[email protected]"};
mailInfo.setSendAddress(destination);
mailInfo.setUsername("leeposter");
mailInfo.setValidate("true");
mailInfo.setPassword("****");
try{
boolean flag=mail.Send(mailInfo);
if(flag==true){
System.out.println("发送成功");
}else{
System.out.println("发送失败");
}
}catch(Exception e){
e.printStackTrace();
}
}
}