javamail发送邮件

来源:互联网 发布:mysql小于号转义 编辑:程序博客网 时间:2024/06/06 00:53
package test;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
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 TestSend{
private static Properties props = new Properties();
private static MimeMessage mimeMsg;

public static void sendMail(String smtp, String username, String password,
String toMail, String title, String text /**String htmlSubject,
String htmlcontent, String filename, String AttacheSubject*/) {

props.put("mail.smtp.host", smtp);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", 25);
String fromMail = username;
// 创建密码验证器
Authenticator authenticator = new MyAuthenticator(username, password);
// 获取基于Properties Session对象
Session session = Session.getDefaultInstance(props, authenticator);
session.setDebug(true);
// 根据Session创建一个邮件消息
mimeMsg = new MimeMessage(session);
// 创建邮件发送者地址
try {
// 创建邮件发送者地址
Address fromAdd = new InternetAddress(fromMail, "发信者");
mimeMsg.setFrom(fromAdd);
// 创建邮件的接收者地址,并设置到邮件消息中
Address toAdd = new InternetAddress(toMail);
mimeMsg.setRecipient(Message.RecipientType.TO, toAdd);
// 设置邮件消息发送的时间
mimeMsg.setSentDate(new Date());
// 简单文本
mimeMsg.setSubject(title);
mimeMsg.setText(text);
// 发送邮件
Transport trans = session.getTransport("smtp");
trans.connect(smtp, username, password);
trans.sendMessage(mimeMsg, new Address[] { new InternetAddress(
toMail) });
System.err.println("发送邮件成功");
trans.close();
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
TestSend.sendMail(
"smtp.163.com",
"用户名",
"密码",
"发送到的邮箱",
"简单文本邮件标题",
"这是一个简单文本邮件\r\n支持换行 "
);
}
}
原创粉丝点击