工做中有java邮件发送 用了原生的javax.mail 分享一下html
// MailUtils
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.ibatis.io.Resources;
public class MailUtils {
public static String sendMail(String title, String content, String ToAdress, String Toname, String fromName) {
String sendStatic = MailStatus.FAIL.getTitle();
try {
Properties propsMail = Resources.getResourceAsProperties("jdbc.properties");
String host = propsMail.getProperty("mailHost");
String port = propsMail.getProperty("mailPort");
/* * Properties是一个属性对象,用来建立Session对象 */
Properties props = new Properties();
props.setProperty("mail.smtp.host", host);
props.setProperty("mail.smtp.port", port);
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.ssl.enable", "false");// "true"
props.setProperty("mail.smtp.connectiontimeout", "5000");
final String user = propsMail.getProperty("mailUserName");// 用户名
final String pwd = propsMail.getProperty("mailUserPass");// 密码
/* * Session类定义了一个基本的邮件对话。 */
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 登陆用户名密码
return new PasswordAuthentication(user, pwd);
}
});
session.setDebug(true);
/* * Transport类用来发送邮件。 传入参数smtp,transport将自动按照smtp协议发送邮件。 */
Transport transport = session.getTransport("smtp");
transport.connect(host, user, pwd);
/* * Message对象用来储存实际发送的电子邮件信息 */
MimeMessage message = new MimeMessage(session);
message.setSubject(title);
// 消息发送者接收者设置(发件地址,昵称),收件人看到的昵称是这里设定的
message.setFrom(new InternetAddress(user, fromName));
message.addRecipients(Message.RecipientType.TO,
new InternetAddress[] { new InternetAddress(ToAdress, Toname), });
message.saveChanges();
// 设置邮件内容及编码格式
// 后一个参数能够不指定编码,如"text/plain",可是将不能显示中文字符
message.setContent(content, "text/html;charset=utf-8");
Transport.send(message);
transport.close();
sendStatic = MailStatus.SUCCESS.getTitle();
} catch (Exception e) {
sendStatic = MailStatus.FAIL.getTitle();
System.exit(0);
}
return sendStatic;
}
public static void main(String[] args) {
MailUtils ma = new MailUtils();
ma.sendMail("标题", "你好你的邮件", "xxxx@xxxx", "发送姓名", "系统提示");
System.exit(0);
}
}
复制代码
public enum MailStatus {
SUCCESS("SUCCESS", "1"), FAIL("FAIL", "0");
// 成员变量
private String title;
private String content;
// 构造方法
private MailStatus(String title, String content) {
this.title = title;
this.content = content;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
复制代码