一、采用的是QQ的smtp服务器发送邮件,其它服务器没验证html
二、须要QQ邮箱的POP3|SMTP服务开启,而且拷贝下受权码代码中会用到java
import java.util.Calendar;
import java.util.Properties;安全
import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;服务器
/*
* 使用JavaMail API 在Java程序中发送e-mail
*/
public class SendEmail {
/*
* param:
* smtpHost:服务器域名,这里采用的是QQ邮箱的smtp服务器
* from:你的要发送邮件的邮箱
* fromUserPassword:要发送邮箱的密码
* to:收件人的邮箱
* subject:发送的邮件的主题
* messageText:邮件正文
* messageType:发送内容的格式
*/
@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", "465");
props.put("mail.smtp.auth", "true"); //使用验证
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.ssl.enable", "true");
//props.put("mail.debug", "true");
Session mailSession = Session.getInstance(props, new MyAuthenticator(from,"*************"));
//Session mailSession = Session.getDefaultInstance(props,null);
//二、编写消息
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,from,fromUserPassword);
transport.connect(from, fromUserPassword);
transport.send(message, message.getRecipients(RecipientType.TO));
System.out.println("message yes");
}
public static void main(String[] args) {
try {
sendMessage("smtp.qq.com",
"yourqqmail@qq.com",
"yourmailpassword",
"你的任意邮箱地址",
"nihao",
"<<<<<>>>>>>",
"text/html;charset=gb2312");
} catch (Exception e) {
e.printStackTrace();
}
}
}网络
/*
* 注意:参数 password 为 POP3/SMTP 的受权码 (16位),而不是邮箱密码session
* 就是上边提到的从QQ邮箱获取的受权码
*/
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);
}
}this
备注:代码主体来自于网络上的前辈,在下只是在前辈基础上作了微调,若有雷同,请原谅我吧~~~~~~~~在此对其分享表示感谢O(∩_∩)O哈!
spa