本文贴上发送带附件的邮件代码,要用到一个JAR包 activation.jar
这个代码完整 直接复制就可以运行了
package org.fantlam;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
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;
public class JavaMail3 {
/**
* @param args
*/
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
String tto="[email protected]";//收件人地址
String ttitle="这是邮件的标题";
String tcontent="这是邮件的内容";
String tfj="D:\\Downloads\\dbschema.sql";//附件内容
Properties props=new Properties();
props.put("mail.smtp.host","smtp.126.com");
props.put("mail.smtp.auth","true");
Session s=Session.getInstance(props);
s.setDebug(true);
MimeMessage message=new MimeMessage(s);
//给消息对象设置发件人/收件人/主题/发信时间
InternetAddress from=new InternetAddress("[email protected]");
message.setFrom(from);
InternetAddress to=new InternetAddress(tto);
message.setRecipient(Message.RecipientType.TO,to);
message.setSubject(ttitle);
message.setSentDate(new Date());
Multipart test=new MimeMultipart();//新建一个MimeMultipart对象用来存放多个BodyPart对象
//设置信件文本内容
BodyPart mdp=new MimeBodyPart();//新建一个存放信件内容的BodyPart对象
mdp.setContent(tcontent,"text/html;charset=gb2312");//给BodyPart对象设置内容和格式/编码方式
test.addBodyPart(mdp);//将含有信件内容的BodyPart加入到MimeMultipart对象中
//设置信件的附件
mdp=new MimeBodyPart();
FileDataSource fds=new FileDataSource(tfj);
DataHandler dh=new DataHandler(fds);
int i=tfj.lastIndexOf("\\");
String fname=tfj.substring(i);//提取文件名
mdp.setFileName(fname);//可以和原文件名不一致,但最好一样
mdp.setDataHandler(dh);
test.addBodyPart(mdp);
message.setContent(test);//把mm作为消息对象的内容
message.saveChanges();
Transport transport=s.getTransport("smtp");
transport.connect("smtp.126.com",[email protected]","密码");
transport.sendMessage(message,message.getAllRecipients());
transport.close();
}
}