package TestMail;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail
{
public static void main(String[] args) throws Exception
{
sendMail();
}
public static void sendMail()throws Exception
{
// //创建配置信息
Properties props = new Properties();
//标准验证的信息"smtp.qq.com"发送给qq可以修改为sina或者其他.
props.put("mail.smtp.host", "smtp.qq.com");
//设置是否要验证
props.put("mail.smtp.auth", "true");
//验证信息
Authenticator auth= new Authenticator() {
public PasswordAuthentication getPasswordAuthentication()
{
//例如我的
PasswordAuthentication pa =new PasswordAuthentication("123456不需要输入@qq.com","密码");
return pa;
}
};
try {
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
//设置发送者的邮箱
Address from =new InternetAddress("123456@qq.com");
//是否在控制台显示发送的情况默认是false
session.setDebug(true);
Transport ta = session.getTransport(from);
msg.setFrom(from);
//设置发送的地址
msg.setRecipient(RecipientType.TO,new InternetAddress("56789@qq.com"));
//设置发送文本的主题
msg.setSubject("JavaMail hello world example");
msg.setText("java test");
//设置发送的文本的内容
msg.setContent("java Test mail","text/html;charset=UTF-8");
ta.send(msg);
} catch (MessagingException mex) {
System.out.println("send failed, exception: " + mex);
}
}
}
|