以下是发送邮件的一个工具类。
使用maven的话,在pom.xml中添加
<!-- 邮件java mail -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.2</version>
</dependency>
public class Mail {
public static final String MODE_TEXT = "text/plain;charset=gb2312";
public static final String MODE_HTML = "text/html;charset=gb2312";
private String smtpHost = "mail.aspirecn.com";
private String smtpPort = "587";
private String smtpUser = "wangzeren";
private String smtpPassword ="xiaoren27!" ;
private boolean isAuthenticationSMTP = true;
private boolean isTLS = true;
private String from = "wangzeren@aspirecn.com";
private Address[] to = null;
private Address[] cc = null;
private Address[] bcc = null;
private String subject = "资金预警信息";
private String content = "";
private String content_type = MODE_TEXT;
private Vector<File> vFiles = new Vector<File>();public Mail() {
}public Mail(String smtpHostName, String smtpUser, String smtpPassword,
String fromAddress, String toAddress, String subject, String content) {
this.smtpHost = smtpHostName;
this.smtpUser = smtpUser;
this.smtpPassword = smtpPassword;
this.isAuthenticationSMTP = true;
this.from = fromAddress;
this.to = getAddress(toAddress);
this.subject = subject;
this.content = content;
}
public Mail(String toAddress, String subject, String content) {
this.smtpHost =ConfProperties.MAIL_SMS_HOST;//邮件服务器地址
this.smtpUser = ConfProperties.MAIL_SMTP_USER;//发件人用户名
this.smtpPassword = ConfProperties.MAIL_SMTP_PASSWORD;/发件人/密码
this.isAuthenticationSMTP = true;
this.smtpPort=ConfProperties.MAIL_SMTP_PORT;//端口号
this.from = ConfProperties.MAIL_FROM;//发件人
this.to = getAddress(toAddress);//收件人
this.subject = subject;//标题
this.content = content;//内容
}
public void setSmtpHost(String server) {
this.smtpHost = server;
}
public void setSmtpHost(String server, String port) {
this.smtpHost = server;
this.smtpPort = port;
}
public void setTo(String aEmail) {
String[] s = new String[1];
s[0] = aEmail;
this.to = getAddress(s);
}
public void setTo(String[] Emails) {
this.to = getAddress(Emails);
}
public void setCC(String aEmail) {
String[] s = new String[1];
s[0] = aEmail;
this.cc = getAddress(s);
}
public void setCC(String[] Emails) {
this.cc = getAddress(Emails);
}
public void setBCC(String aEmail) {
String[] s = new String[1];
s[0] = aEmail;
this.bcc = getAddress(s);
}
public void setBCC(String[] Emails) {
this.bcc = getAddress(Emails);
}
public void setFrom(String aEmail) {
this.from = aEmail;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setBody(String mailContent) {
this.content = mailContent;
}
public void setContentType(String contentType) {
this.content_type = contentType;
}
public void setSmtpAuthentication(String username, String password) {
this.smtpUser = username;
this.smtpPassword = password;
this.isAuthenticationSMTP = true;
}
public void setTLS(boolean isTLS) {
this.isTLS = isTLS;
}
public void addAttachment(File afile) {
vFiles.add(afile);
}
public boolean hasAttachment() {
return vFiles.size() > 0;
}
public void send() throws AddressException, MessagingException,
UnsupportedEncodingException, IllegalArgumentException {
if (isEmpty(this.smtpHost)) {
throw new IllegalArgumentException("Please set SMTP host");
}
Properties props = getSmtpProperties();
Session conn = Session.getInstance(props, null);
conn.setDebug(true);
MimeMessage msg = new MimeMessage(conn);
if (isEmpty(this.from)) {
throw new IllegalArgumentException("Please set FROM address");
} else {
msg.setFrom(new InternetAddress(this.from));
}
if (this.to != null) {
msg.setRecipients(Message.RecipientType.TO, this.to);
}
if (this.cc != null) {
msg.setRecipients(Message.RecipientType.CC, this.cc);
}
if (this.bcc != null) {
msg.setRecipients(Message.RecipientType.BCC, this.bcc);
}
sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
msg.setSubject("=?GB2312?B?" + enc.encode(this.subject.getBytes())
+ "?=");
if (!hasAttachment()) {
if (this.isHtmlModeMail()) {
msg.setContent(this.content, this.content_type);
} else {
msg.setText(this.content);
}
} else {
Multipart mp = new MimeMultipart();
MimeBodyPart mbp = null;
mbp = new MimeBodyPart();
mbp.setContent(this.content, this.content_type);
mp.addBodyPart(mbp);
msg.setContent(mp);
for (int i = 0; i < vFiles.size(); i++) {
mbp = new MimeBodyPart();
File file = (File) vFiles.get(i);
FileDataSource fds = new FileDataSource(file);
mbp.setDataHandler(new DataHandler(fds));
mbp.setFileName(MimeUtility.decodeText(file.getName()));
mp.addBodyPart(mbp);
}
}
msg.saveChanges();
if (this.isAuthenticationSMTP) {
Transport transport = conn.getTransport("smtp");
try {
transport.connect(this.smtpHost, this.smtpUser,
this.smtpPassword);
transport.sendMessage(msg, msg.getAllRecipients());
} catch (MessagingException e) {
throw e;
} finally {
transport.close();
}
} else {
Transport.send(msg, msg.getAllRecipients());
}
}
public Properties getSmtpProperties() {
Properties props = new Properties();
if (this.isTLS) {
props.put("mail.smtp.host", this.smtpHost);
props.put("mail.smtp.port", this.smtpPort);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.socketFactory.port", this.smtpPort);
props.put("mail.smtp.socketFactory.fallback", "false");
props.put("mail.smtp.connectiontimeout", "16000");
props.put("mail.smtp.timeout", "16000");
} else {
props.put("mail.smtp.host", this.smtpHost);
props.put("mail.smtp.port", this.smtpPort);
if (this.isAuthenticationSMTP) {
props.put("mail.smtp.auth", "true");
}
}
return props;
}
private Address[] getAddress(String[] add) {
Address[] a = new Address[add.length];
for (int i = 0; i < add.length; i++) {
try {
a[i] = new InternetAddress(add[i]);
} catch (AddressException ex) {
ex.printStackTrace();
}
}
return a;
}
private Address[] getAddress(String adds) {
if (adds != null && !adds.equals("")) {
String[] add = adds.split(";");
return getAddress(add);
} else {
return null;
}
}
private boolean isHtmlModeMail() {
return this.content_type.equals(MODE_HTML);
}
private boolean isEmpty(String str) {
if (str == null || "".equals(str)) {
return true;
} else {
return false;
}
}
/**
* @param args
* @throws MessagingException
* @throws IllegalArgumentException
* @throws UnsupportedEncodingException
* @throws AddressException
*/
public static void main(String[] args) throws AddressException,
UnsupportedEncodingException, IllegalArgumentException,
MessagingException {
Mail mail = new Mail("mail.aspirecn.com",
"wangzeren",
"xiaoren27!", "wangzeren@aspirecn.com",
"wangzeren@aspirecn.com", "impp", "");
mail.addAttachment(new File("附件.txt"));//添加附件
}
}
另外,可能需要将邮箱服务器的证书添加到jdk,可以参考这篇文章http://www.cnblogs.com/langtianya/p/3334493.html