代码如下:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Jmail {
public static void main(String[] args) {
// jmail1();
jmail2();
}
private static void jmail2() {
try{
String tto = "xxxxxxxxxxx@qq.com";
String ttitle = "测试jmail";
String tcontent = "测试成功";
Properties props=new Properties();
props.put("mail.smtp.host","smtp.163.com");//选择163服务器
props.put("mail.smtp.auth","true");
Session s=Session.getInstance(props);
s.setDebug(true);
MimeMessage message=new MimeMessage(s);
//给消息对象设置发件人/收件人/主题/发信时间
InternetAddress from=new InternetAddress("xxxxxxxxx@163.com");//必须拥有163邮箱
message.setFrom(from);
InternetAddress to=new InternetAddress(tto);
message.setRecipient(Message.RecipientType.TO,to);
message.setSubject(ttitle);
message.setSentDate(new Date());
//给消息对象设置内容
BodyPart mdp=new MimeBodyPart();//新建一个存放信件内容的BodyPart对象
mdp.setContent(tcontent,"text/html;charset=gb2312");//给BodyPart对象设置内容和格式/编码方式
Multipart mm=new MimeMultipart();//新建一个MimeMultipart对象用来存放BodyPart对
//象(事实上可以存放多个)
mm.addBodyPart(mdp);//将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
message.setContent(mm);//把mm作为消息对象的内容
message.saveChanges();
Transport transport=s.getTransport("smtp");
transport.connect("smtp.163.com","xxxxxxxxxx","xxxxxx");//163邮箱的用户名和密码
transport.sendMessage(message,message.getAllRecipients());
transport.close();
}catch(MessagingException e){
System.out.println(e.toString());
}
}
}