导入jar包:mail.jar
/**
* @author:田坤* @E-mail:977559644@qq.com
* @version 创建时间:2016年8月9日 上午9:27:15
* @TODO
*/
package util;
import java.util.Calendar;
import java.util.Properties;
import javax.mail.Authenticator;
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 test {
@SuppressWarnings("static-access")
public static void sendMessage(String smtpHost, String from,
String fromUserPassword, String to, String subject,
String messageText, String messageType) throws MessagingException {
// 第一步:配置javax.mail.Session对象
System.out.println("为" + smtpHost + "配置mail session对象");
Properties props = new Properties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.starttls.enable","true");//使用 STARTTLS安全连接
//props.put("mail.smtp.port", "25"); //google使用465或587端口
props.put("mail.smtp.auth", "true"); // 使用验证
//props.put("mail.debug", "true");
Session mailSession = Session.getInstance(props,new MyAuthenticator(from,fromUserPassword));
// 第二步:编写消息
System.out.println("编写消息from——to:" + from + "——" + to);
InternetAddress fromAddress = new InternetAddress(from);
InternetAddress toAddress = new InternetAddress(to);
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(fromAddress);
message.addRecipient(RecipientType.TO, toAddress);
message.setSentDate(Calendar.getInstance().getTime());
message.setSubject(subject);
message.setContent(messageText, messageType);
// 第三步:发送消息
Transport transport = mailSession.getTransport("smtp");
transport.connect(smtpHost,"tk13473995461", fromUserPassword);
transport.send(message, message.getRecipients(RecipientType.TO));
System.out.println("message yes");
}
public static void main(String[] args) {
try {
/*
* 1.发件人的smtp服务器,注意是否开通
* 2.发件人邮箱
* 3.发件人密码
* 4.收件人邮箱
* 5.标题
* 6.内容
* 7.编码格式,一般为:text/html;charset=utf-8
*/
test.sendMessage("smtp.sina.com", "tk13473995461@sina.com",
"********", "52463038@qq.com", "nihao",
"哈哈,这是我用java代码给你发的邮件,哈哈哈哈",
"text/html;charset=utf-8");
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class MyAuthenticator extends Authenticator{
String userName="";
String password="";
public MyAuthenticator(){
}
public MyAuthenticator(String userName,String password){
this.userName=userName;
this.password=password;
}
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(userName, password);
}
}
这里是用sina邮箱发送邮件,目标邮箱为qq邮箱
使用qq邮箱发送会报错:535 Error: ÇëʹÓÃÊÚȨÂëµÇ¼¡£ÏêÇéÇë¿´: http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
还没解决这个问题。。。
注意查看发送邮箱的stmp协议服务器,以及看看自己是否开通了stmp协议。一般在邮箱设置里面有