在此分享互相交流学习,如有问题请指正
javax.mail.* 下载地址:http://download.csdn.net/detail/daohaode123/8394273
package com.zjl;
import java.util.Date;
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 org.junit.Test;
public class Email {
/**
* 发送带附件的邮件
* @param formAddr
* @param toAddr
* @param subject
* @param content
* @param affixPath 附件路径
* @return
* @throws Exception
*/
public boolean sendEmailIncludingAffix(String host, String formAddr, String toAddr,
String subject, String content, String affixPath) throws Exception{
Properties prop = new Properties();
prop.put("mail.smtp.auth", false);//不进行邮件用户名 、密码验证
prop.put("mail.smtp.host", host);
Session session = Session.getDefaultInstance(prop);
session.setDebug(true);//此处会在控制台打印发送邮件的调用过程
MimeMessage message = new MimeMessage(session);
try{
message.setFrom(new InternetAddress(formAddr));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddr));
message.setSentDate(new Date());
message.setSubject(subject);
Multipart mutiPart = new MimeMultipart();
// 添加邮件
BodyPart contentpart = new MimeBodyPart();
contentpart.setText(content);
mutiPart.addBodyPart(contentpart);
//添加附件
BodyPart bp = new MimeBodyPart();
DataSource datasource = new FileDataSource(affixPath);
bp.setDataHandler(new DataHandler(datasource));
bp.setFileName(datasource.getName());
mutiPart.addBodyPart(bp);
message.setContent(mutiPart);
//保存邮件
message.saveChanges();
//发送邮件
Transport.send(message);
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}
}
@Test
public void Test(){
try {
boolean isSucess = sendEmailIncludingAffix("8.99.5.116","123@qq.com","234@qq.com","主题","测试发邮件","D:\\email.xls");
if(isSucess){
System.out.println("发送成功");
}else{
System.out.println("登录失败");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}