采用Java给指定(一位或多位)邮箱用户发送指定内容的邮件:
package com.jeelon.util;
import java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
/**
* java 发送Email
*
* @author 冯旭
*
*/
public class SendEmail {
/**
* 采用给定协议和服务器发送邮件
*
* @author 冯旭
* @param sendEmail
* :发送给指定用户的邮件
* @param content
* :发送内容
* @param SendUserEmail
* :发件人邮箱地址
* @param SendUserEmailPwd
* :发件人邮箱地址登录密码
* @param sendMethod
* :发件方使用邮箱的的协议方式。如:POP3、SMTP
* @param sendSystemAddress
* :使用协议方式的服务器。如SMTP方式下163邮箱和QQ服务器分别为:smtp.163.com、smtp.qq.com
* @return boolean: 是否发送成功
*/
public static boolean sendEmial(final String[] sendEmail,
final String content, final String SendUserEmail,
final String SendUserEmailPwd, final String sendMethod,
final String sendSystemAddress) {
try {
Properties props = new Properties();
props.put("mail.smtp.host", sendSystemAddress);// 发件人使用发邮件的电子邮箱服务器
props.put("mail.smtp.auth", "true");// 同时通过验证
Session s = Session.getInstance(props);// 根据属性新建一个邮件会话
s.setDebug(true);
MimeMessage message = new MimeMessage(s);// 由邮件会话新建一个消息对象
InternetAddress[] addess = new InternetAddress[sendEmail.length];
for (int i = 0; i < sendEmail.length; i++) {
addess[i] = new InternetAddress(sendEmail[i]);
}
// 设置邮件
message.setFrom(new InternetAddress(SendUserEmail));// 设置发件人
message.setRecipients(Message.RecipientType.TO, addess);
message.setSubject("本次邮件的主题");
// 发送HTML格式
Multipart mimeBodyPart = new MimeMultipart();
BodyPart html = new MimeBodyPart();
html.setContent(content, "text/html;charset=utf-8");
mimeBodyPart.addBodyPart(html);
message.setContent(mimeBodyPart);
message.setSentDate(new java.util.Date());// 设置发信时间
// 发送邮件
message.saveChanges();// 存储邮件信息
Transport transport = s.getTransport(sendMethod);
transport.connect(sendSystemAddress, SendUserEmail, SendUserEmailPwd);// 以smtp方式登录邮箱 smtp.163.com:登录邮箱所在的服务器
transport.sendMessage(message, message.getAllRecipients());// 发送邮件,其中第二个参数是所有
return true;
} catch (AddressException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
return false;
}
}
测试:
private SendEmailService ses = new SendEmailService();
public String emailSend() {
ses.send(new String[] { "630923.hi@163.com", "360037589@qq.com" },
"<a href='http://www.baidu.com'>www.baidu.com</a>",
"360037589@qq.com", "f3600fd389", "smtp", "smtp.qq.com");
return "send";
}