package com;
import java.util.Properties;
import javax.mail.Authenticator;
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;
import com.abcchina.PopupAuthenticator;
public class Send {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
String host = "smtp.ym.163.com"; // 163免费企业邮箱的smtp服务器
String from = "[email protected]"; // 我的企业邮箱地址
String to = "[email protected]"; // 邮件要发送到的邮箱地址
String username = "web";
String password = "******"; //
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", host);
String content = "hello";
String subJect="这是一个好消息1";
//认证的时候用的是 邮箱全拼 密码 而不是用户 密码 这点要注意
Authenticator smtpAuth = new PopupAuthenticator(
from, password);
Session session = Session.getDefaultInstance(props, smtpAuth);
session.setDebug(true);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
BodyPart mdp = new MimeBodyPart();
mdp.setContent(content, "text/html;charset=gb2312");
Multipart mm = new MimeMultipart();
mm.addBodyPart(mdp);
message.setContent(mm);
message.setSubject(subJect);
message.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host, username, password);//链接的时候用的是 用户名 密码 而不是邮箱全拼 密码 这点要注意
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
}
=======================================================
package com.abcchina;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class PopupAuthenticator extends Authenticator {
String username=null;
String password=null;
public PopupAuthenticator(){}
public PopupAuthenticator(String username,String password
){
this.username=username;
this.password=password;
}
public PasswordAuthentication performCheck(String user,String pass){
username = user;
password = pass;
return getPasswordAuthentication();
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
有什么不明白的直接评论即可!!!
版权声明:本文为博主原创文章,未经博主允许不得转载。