这是一个简易的JavaMial 实现
下载javamail 包,将其添加到项目的libraries
package Basic;
import static Basic.print.*;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class HelloJMail {
public HelloJMail() {
init();
}
public void init() {
Authenticator auth = new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
};
// 创建Properties 对象
Properties props = System.getProperties();
// 设置发送邮件的邮件服务器的属性(这里使用网易的smtp服务器)
props.put(MAIL_SMTP_HOST, host);
// 需要经过授权,也就是有户名和密码的校验,这样才能通过验证(一定要有这一条)
props.put(MAIL_SMTP_AUTH, "true");
// 用刚刚设置好的props对象构建一个会话
session = Session.getDefaultInstance(props, auth);
try {
// 发送邮件
transport = session.getTransport("smtp");
// 连接服务器的邮箱
transport.connect(host, username, password);
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
print("与 " + host + " 成功建立会话");
}
private Message createMessage() throws AddressException, MessagingException {
// 用session为参数定义消息对象
MimeMessage message = new MimeMessage(session);
// 用session为参数定义消息对象
message.setFrom(new InternetAddress(from));
message.setSentDate(new Date());
// 加载收件人地址
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// 加载标题
message.setSubject("Hello KM");
message.setText("A JavaMail Try!");
// 发送消息
Transport.send(message);
// 保存邮件
message.saveChanges();
return message;
}
public void send(boolean debug) {
session.setDebug(debug);
try {
Message message = createMessage();
transport.sendMessage(message, message.getAllRecipients());
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
print("邮件成功发送! TO : " + to);
}
public void close() throws MessagingException {
if (null != transport)
transport.close();
}
public static void main(String[] args) {
boolean debug = false;
HelloJMail mail = new HelloJMail();
// 设置smtp服务器以及邮箱的帐号和密码
mail.send(debug);
try {
if (null != mail) {
mail.close();
}
} catch (MessagingException e) {
e.printStackTrace();
}
}
private String host = "smtp.163.com"; // 指定的smtp服务器
private String from = "javamial123@163.com"; // 邮件发送人的邮件地址
private String to = "12345678@qq.com"; // 邮件接收人的邮件地址
private final String username = "qweqweqwe"; // 发件人的邮件帐户
private final String password = "asdasd"; // 发件人的邮件密码
private final String MAIL_SMTP_HOST = "mail.smtp.host";
private final String MAIL_SMTP_AUTH = "mail.smtp.auth";
private Session session; // 会话
private Transport transport; // 发送邮件
// private MailAddress mailAddress; //收件人地址
// private MailBody mailBody; //邮件内容
}