标签:
JAVA MAIL是利用现有的邮件账户发送邮件的工具,比如说,我在网易注册一个邮箱账户,通过JAVA Mail的操控,我可以不亲自登录网易邮箱,让程序自动的使用网易邮箱发送邮件。这一机制被广泛的用在注册激活和垃圾邮件的发送等方面。
JAVA邮件发送的大致过程是这样的的:
1、构建一个继承自javax.mail.Authenticator的具体类,并重写里面的getPasswordAuthentication()方法。此类是用作登录校验的,以确保你对该邮箱有发送邮件的权利。
2、构建一个properties文件,该文件中存放SMTP服务器地址等参数。
3、通过构建的properties文件和javax.mail.Authenticator具体类来创建一个javax.mail.Session。Session的创建,就相当于登录邮箱一样。剩下的自然就是新建邮件。
4、构建邮件内容,一般是javax.mail.internet.MimeMessage对象,并指定发送人,收信人,主题,内容等等。
5、使用javax.mail.Transport工具类发送邮件。
下面是具体代码:
方法一:
/**
* @ClassName : Authentication
* @Description : 验证器
* @author : chenrl
* @date : 2015年10月30日 上午9:59:52
*/
public class Authentication extends Authenticator {
String username=null;
String password=null;
public Authentication(){
}
public Authentication(String username, String password) {
this.username = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication(){
PasswordAuthentication pa = new PasswordAuthentication(username, password);
return pa;
}
}
public class SendMail {
// 发送邮件的服务器的IP和端口
private String mailServerHost;
private String mailServerPort = "25";
private String fromAddress;
private String toAddress;
private String userName;
private String password;
private boolean validate = false;
private String subject;
private String content;
private String[] attachFileNames;
/**
* 获得邮件会话属性
*/
public Properties getProperties() {
Properties p = new Properties();
p.put("mail.smtp.host", this.mailServerHost);
p.put("mail.smtp.port", this.mailServerPort);
p.put("mail.smtp.auth", validate ? "true" : "false");
return p;
}
//set get
}
public class MailSend {
public boolean sendTextMail(final SendMail mailInfo) {
// 判断是否需要身份认证
Authentication authenticator = null;
Properties pro = mailInfo.getProperties();
if (mailInfo.isValidate()) {
// 如果需要身份认证,则创建一个密码验证器
authenticator = new Authentication(mailInfo.getUserName(), mailInfo.getPassword());
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
/*Session sendMailSession = Session.getDefaultInstance(pro,authenticator); */
Session sendMailSession = Session.getDefaultInstance(pro, new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(mailInfo.getUserName(), mailInfo.getPassword());
}
});
try {
Message mailMessage = new MimeMessage(sendMailSession);
Address from = new InternetAddress(mailInfo.getFromAddress());
mailMessage.setFrom(from);
Address to = new InternetAddress(mailInfo.getToAddress());
mailMessage.setRecipient(Message.RecipientType.TO,to);
mailMessage.setSubject(mailInfo.getSubject());
mailMessage.setSentDate(new Date());
String mailContent = mailInfo.getContent();
mailMessage.setText(mailContent);
Transport.send(mailMessage);
return true;
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
}
/**
* 以HTML格式发送邮件
*/
public boolean sendHtmlMail(SendMail mailInfo){
// 判断是否需要身份认证
Authentication authenticator = null;
Properties pro = mailInfo.getProperties();
if (mailInfo.isValidate()) {
authenticator = new Authentication(mailInfo.getUserName(), mailInfo.getPassword());
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
try {
// 根据session创建一个邮件消息
Message mailMessage = new MimeMessage(sendMailSession);
Address from = new InternetAddress(mailInfo.getFromAddress());
mailMessage.setFrom(from);
Address to = new InternetAddress(mailInfo.getToAddress());
// Message.RecipientType.TO属性表示接收者的类型为TO
mailMessage.setRecipient(Message.RecipientType.TO,to);
mailMessage.setSubject(mailInfo.getSubject());
mailMessage.setSentDate(new Date());
Multipart mainPart = new MimeMultipart();
BodyPart html = new MimeBodyPart();
html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
mainPart.addBodyPart(html);
mailMessage.setContent(mainPart);
Transport.send(mailMessage);
return true;
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
}
}
public class Send {
public static void main(String[] args) {
//设置邮件参数
SendMail mail = new SendMail();
//qq邮箱
//mail.setMailServerHost("smtp.qq.com"); //这里填发送者的邮箱服务器,我以qq举个例子
//sina
mail.setMailServerHost("smtp.sina.com");
mail.setMailServerPort("25");
mail.setValidate(true);
/*
mail.setUserName("发送者的邮箱名字");
mail.setPassword("发送者邮箱密码");
mail.setFromAddress("发送者邮箱名字");
mail.setToAddress("接受者邮箱密码");
mail.setSubject("标题");
mail.setContent("内容"); */
/*qq邮箱测试成功*/
/*163邮箱测试失败*/
/*gov.cn邮箱测试失败*/
/*sina邮箱测试成功*/
//发送邮件
MailSend sms = new MailSend();
sms.sendTextMail(mail);//发送文体格式
sms.sendHtmlMail(mail);//发送html格式
}
}
方法二:用下面的方法也可以实现:
/****************************************************************
* 对QQ邮箱使用(对于其他的使用类似的你应该也会更改了)
* 首先把QQ邮箱的POP3 SMTP打开
* 首先确定你的网络正常、非代理
* 确定你的QQ邮箱开启了SMTP
* 如果没有开启,那么这样设置下
* 设置->账户 --在下面-- 把这个选上 [√]SMTP发信后保存到服务器
****************************************************************/
public class SendEmail {
//设置服务器
private static String KEY_SMTP = "mail.smtp.host";
private static String VALUE_SMTP = "smtp.qq.com";
//服务器验证
private static String KEY_PROPS = "mail.smtp.auth";
private static boolean VALUE_PROPS = true;
//发件人用户名、密码
private String SEND_USER = EmailConfProperties.getEmail();//你的QQ邮箱
private String SEND_UNAME = EmailConfProperties.getEmailName(); //你的邮箱名
private String SEND_PWD = EmailConfProperties.getEmailPwd(); //你的邮箱密码
//建立会话
private MimeMessage message;
private Session s;
/*
* 初始化方法
* */
public SendEmail(){
Properties props = System.getProperties();
props.setProperty(KEY_SMTP, VALUE_SMTP);
props.put(KEY_PROPS, VALUE_PROPS);
s = Session.getInstance(props);
s.setDebug(true);//开启后有调试信息
message = new MimeMessage(s);
}
/**
* 发送邮件
* @param headName 邮件头文件名
* @param sendHtml 邮件内容
* @param receiveUser 收件人184172133@qq.com
*/
public void doSendHtmlEmail(String headName,StringBuffer sendHtml,String receiveUser){
try {
// 发件人
InternetAddress from = new InternetAddress(SEND_USER);
message.setFrom(from);
// 收件人
InternetAddress to = new InternetAddress(receiveUser);
message.setRecipient(Message.RecipientType.TO, to);
// 邮件标题
message.setSubject(headName);
String content = sendHtml.toString();
// 邮件内容,也可以使纯文本"text/plain"
message.setContent(content, "text/html;charset=GBK");
message.saveChanges();
Transport transport = s.getTransport("smtp");
// smtp验证,就是你用来发邮件的邮箱用户名密码
transport.connect(VALUE_SMTP, SEND_UNAME, SEND_PWD);
// 发送
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//发邮件提醒
SendEmail email = new SendEmail();
String server_IP = EmailConfProperties.getServerIP();
String server_Port = EmailConfProperties.getServerPort();
String server_Name = EmailConfProperties.getServerName();
String path = "http://" + server_IP + ":" + server_Port + "/" + server_Name;
String headName = "用户注册信息审核通知";
StringBuffer sendHtml = new StringBuffer("亲爱的用户,您好:" +
"<br> 验证码已经发送到您的邮箱,请尽快完成密码找回功能,验证码为:" + 123 +
"<br> 您可以:<a href=‘" + path + "‘>点击此处登录</a>" +
"<br><br>系统邮件,请勿回复");
String receiveUser = "users516@163.com";
email.doSendHtmlEmail(headName, sendHtml, receiveUser);
// System.out.println("邮件已发出,请注意查收!");
}
}
public class EmailConfProperties {
private static Properties properties;
static {
properties = null;
try {
if (properties == null) {
properties = new Properties();
properties.load(EmailConfProperties.class.getClassLoader().getResourceAsStream("emailConfig.properties"));
}
} catch (Exception e) {
System.err.println("not find emailConfig.properties");
e.printStackTrace();
}
}
//发件人邮箱
public static String getEmail() {
return properties.getProperty("send_Email");
}
//发件人邮箱名
public static String getEmailName() {
return properties.getProperty("send_EmailName");
}
//发件人邮箱密码
public static String getEmailPwd() {
return properties.getProperty("send_EmailPwd");
}
public static String getServerIP(){
return properties.getProperty("server_IP");
}
public static String getServerPort(){
return properties.getProperty("server_port");
}
public static String getServerName(){
return properties.getProperty("server_Name");
}
}
emailConfig.properties:配置文件
send_Email = 123456789@qq.com
send_EmailName = 123456789
send_EmailPwd = 123456789
server_IP = 192.168.17.92
server_port = 8080
server_Name = ISMS
标签:
原文地址:http://www.cnblogs.com/chenrunlin/p/4936345.html