java web 系统,常用邮件功能,现小结如下。
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class EmailUtil {
private MimeMessage mimeMsg; // MIME邮件对象
private Session session; // 邮件会话对象
private Properties props; // 系统属性
private String username = ""; // smtp认证用户名和密码
private String password = "";
private Multipart mp; // Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象
/**
*
*/
public EmailUtil(String smtp) {
setSmtpHost(smtp);
createMimeMessage();
}
/**
* @param hostName
* String
*/
public void setSmtpHost(String hostName) {
if (props == null)
props = System.getProperties(); // 获得系统属性对象
props.put("mail.smtp.host", hostName); // 设置SMTP主机
}
/**
* @return boolean
*/
public boolean createMimeMessage() {
try {
session = Session.getDefaultInstance(props, null); // 获得邮件会话对象
} catch (Exception e) {
return false;
}
try {
mimeMsg = new MimeMessage(session); // 创建MIME邮件对象
mp = new MimeMultipart();
return true;
} catch (Exception e) {
System.out.println("创建MIME邮件对象失败!" );
e.printStackTrace();
return false;
}
}
/**
* @param need
* boolean
*/
public void setNeedAuth(boolean need) {
//LogLIB.LogRun.info("设置smtp身份认证:mail.smtp.auth = " + need);
if (props == null)
props = System.getProperties();
if (need) {
props.put("mail.smtp.auth", "true");
} else {
props.put("mail.smtp.auth", "false");
}
}
/**
* @param name
* String
* @param pass
* String
*/
public void setNamePass(String name, String pass) {
username = name;
password = pass;
}
/**
* @param mailSubject
* String
* @return boolean
* @throws MessagingException
*/
public boolean setSubject(String mailSubject) throws MessagingException {
System.out.println("设置邮件主题!");
boolean flag = false;
try {
mimeMsg.setSubject(mailSubject);
flag = true;
} catch (Exception e) {
System.out.println("设置邮件主题发生错误!");
e.printStackTrace();
}
return flag;
}
/**
* @param mailBody
* String
*/
public boolean setBody(String mailBody) {
try {
BodyPart bp = new MimeBodyPart();
bp.setContent(
"<meta http-equiv=Content-Type content=text/html; charset=gb2312>"
+ mailBody, "text/html;charset=GB2312");
mp.addBodyPart(bp);
return true;
} catch (Exception e) {
System.out.println("设置邮件正文时发生错误!");
e.printStackTrace();
return false;
}
}
/**
* @param name
* String
* @param pass
* String
* @throws MessagingException
*/
public boolean addFileAffix(String filename) throws MessagingException {
System.out.println("增加邮件附件:" + filename);
try {
BodyPart bp = new MimeBodyPart();
FileDataSource fileds = new FileDataSource(filename);
bp.setDataHandler(new DataHandler(fileds));
bp.setFileName(fileds.getName());
mp.addBodyPart(bp);
return true;
} catch (Exception e) {
System.out.println("增加邮件附件:" + filename + "发生错误!");
e.printStackTrace();
return false;
}
}
/**
* @param name
* String
* @param pass
* String
*/
public boolean setFrom(String from) {
System.out.println("设置发信人!");
try {
mimeMsg.setFrom(new InternetAddress(from)); // 设置发信人
return true;
} catch (Exception e) {
return false;
}
}
/**
* @param name
* String
* @param pass
* String
*/
public boolean setTo(String to) {
if (to == null)
return false;
try {
String[] arr = to.split(",");
int receiverCount = arr.length;
if (receiverCount > 0) {
InternetAddress[] address = new InternetAddress[receiverCount];
for (int i = 0; i < receiverCount; i++) {
address[i] = new InternetAddress(arr[i]);
}
mimeMsg.addRecipients(Message.RecipientType.TO, address);
return true;
}else{
return false;
}
} catch (Exception e) {
return false;
}
}
/**
* @param name
* String
* @param pass
* String
*/
public boolean setCopyTo(String copyto) {
if (copyto == null)
return false;
try {
mimeMsg.setRecipients(Message.RecipientType.CC, InternetAddress
.parse(copyto));
return true;
} catch (Exception e) {
return false;
}
}
/**
* @param name
* String
* @param pass
* String
* @throws Exception
*/
public boolean sendout() throws Exception {
try {
mimeMsg.setContent(mp);
mimeMsg.saveChanges();
System.out.println("正在发送邮件....");
Session mailSession = Session.getInstance(props, null);
Transport transport = mailSession.getTransport("smtp");
transport.connect((String) props.get("mail.smtp.host"), username,
password);
transport.sendMessage(mimeMsg, mimeMsg
.getRecipients(Message.RecipientType.TO));
System.out.println("发送邮件成功!");
transport.close();
return true;
} catch (Exception e) {
System.out.println("邮件发送失败!");
throw e;
}
}
/**
* 发邮件
* @param mailSubject
* @param mailBody
* @param sendToAddress
* @param sendFromAddress
* @param smtp
* @param username
* @param password
* @param filename
* @throws Exception
*/
public static void toSendEmail(String mailSubject, String mailBody,
String sendToAddress, String sendFromAddress, String smtp,
String username, String password, String filename) throws Exception {
EmailUtil themail = new EmailUtil(smtp);
themail.setNeedAuth(true);
if (themail.setSubject(mailSubject) == false)
return;
if (themail.setBody(mailBody) == false)
return;
if (themail.setTo(sendToAddress) == false)
return;
if (themail.setFrom(sendFromAddress) == false)
return;
if (themail.addFileAffix(filename) == false)
return;
themail.setNamePass(username, password);
if (themail.sendout() == false)
return;
}
/**
* 发邮件
* @param mailSubject
* @param mailBody
* @param sendToAddress
* @param sendFromAddress
* @param smtp
* @param username
* @param password
* @param filename
* @throws Exception
*/
public static void toSendEmail(String mailSubject, String mailBody,
String sendToAddress, String sendFromAddress, String smtp,
String username, String password) throws Exception {
EmailUtil themail = new EmailUtil(smtp);
themail.setNeedAuth(true);
if (themail.setSubject(mailSubject) == false)
return;
if (themail.setBody(mailBody) == false)
return;
if (themail.setTo(sendToAddress) == false)
return;
if (themail.setFrom(sendFromAddress) == false)
return;
themail.setNamePass(username, password);
if (themail.sendout() == false)
return;
}
public static void sendEmailNotFile(String receiver, String title,
String content) throws Exception{
EmailUtil.toSendEmail(title, content, receiver,
Constant.DEFAULT_EMAIL_ADDRESS,//系统默认邮件地址
Constant.DEFAULT_EMAIL_SMTP, //默认SMTP 比如 smtp.exmail.qq.com
Constant.DEFAULT_EMAIL_ADDRESS, //系统默认邮件地址
Constant.DEFAULT_EMAIL_PASSWORD //系统邮箱密码
);
}
public static void sendEmail(String filePath, String receiver, String title,
String content) throws Exception {
EmailUtil.toSendEmail(title, content, receiver,
Constant.DEFAULT_EMAIL_ADDRESS,//系统默认邮件地址
Constant.DEFAULT_EMAIL_SMTP,//默认SMTP 比如 smtp.exmail.qq.com
Constant.DEFAULT_EMAIL_ADDRESS,//系统默认邮件地址
Constant.DEFAULT_EMAIL_PASSWORD,//系统邮箱密码
filePath);
}
public static void main(String[] args) {
try {
EmailUtil.sendEmail("D:/test.txt","qq1@example.com,qq2@example.com", "这是一份测试邮件", "这是一份测试邮件");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}