package com.china08.yxshipin.util;
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.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class YxShiPinSendEmail extends Authenticator {
String userName = null;
String password = null;
public YxShiPinSendEmail() {
}
public YxShiPinSendEmail(String username, String password) {
this.userName = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
/**
* 发送文本邮件
*
* @param mailServerHost
* 邮件协议
* @param mailServerPort
* 端 口
* @param validate
* 是否需要身份验证
* @param userName
* 发送邮件名字
* @param password
* 发送邮件密码
* @param getFromAddress
* 发送者地址
* @param getToAddress
* 接受者地址
* @param subject
* 标题
* @param content
* 内容
* @return
*/
public static boolean sendTextMail(String mailServerHost,
String mailServerPort, boolean validate, String userName,
String password, String fromAddress, String toAddress,
String subject, String content) {
/**
* 获得邮件会话属性
*/
Properties pro = new Properties();
pro.put("mail.smtp.host", mailServerHost);
pro.put("mail.smtp.port", mailServerPort);
pro.put("mail.smtp.auth", validate ? "true" : "false");
// 判断是否需要身份认证
YxShiPinSendEmail passwordAuthentication = null;
if (validate) {
// 如果需要身份认证,则创建一个密码验证器
passwordAuthentication = new YxShiPinSendEmail(userName, password);
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession = Session.getDefaultInstance(pro,
passwordAuthentication);
try {
// 根据session创建一个邮件消息
Message mailMessage = new MimeMessage(sendMailSession);
// 创建邮件发送者地址
Address from = new InternetAddress(fromAddress);
// 设置邮件消息的发送者
mailMessage.setFrom(from);
// 创建邮件的接收者地址,并设置到邮件消息中
Address to = new InternetAddress(toAddress);
mailMessage.setRecipient(Message.RecipientType.TO, to);
// 设置邮件消息的主题
mailMessage.setSubject(subject);
// 设置邮件消息发送的时间
mailMessage.setSentDate(new Date());
// 设置邮件消息的主要内容
mailMessage.setText(content);
// 发送邮件
Transport.send(mailMessage);
return true;
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
}
}
获取栈堆的信息:
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintStream pout = new PrintStream(out);
ex.printStackTrace(pout);
String ret = new String(out.toByteArray());