在下载使用javax.mail的jar包时候,注意:
有的jar没有包含sun的实现,只包含了api,这类jar名称通常为javax.mail-api-x.x.x.jar,在使用smtp协议发邮件过程中会报错:
- java.lang.ClassNotFoundException: com.sun.mail.util.MailLogger
另一种jar是包含了sun的实现的,名称通常为javax.mail-x.x.x.jar,使用smtp协议发邮件正常!
示例代码:
- package test.mail;
- import javax.mail.Message;
- import javax.mail.Session;
- import javax.mail.Transport;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeMessage;
- import java.util.Date;
- import java.util.Properties;
- public class TestMail {
- public static void sendMail(String fromMail, String user, String password,
- String toMail,
- String mailTitle,
- String mailContent) throws Exception {
- Properties props = new Properties(); //可以加载一个配置文件
- // 使用smtp:简单邮件传输协议
- props.put("mail.smtp.host", "smtp.163.com");//存储发送邮件服务器的信息
- props.put("mail.smtp.auth", "true");//同时通过验证
- Session session = Session.getInstance(props);//根据属性新建一个邮件会话
- // session.setDebug(true); //有他会打印一些调试信息。
- MimeMessage message = new MimeMessage(session);//由邮件会话新建一个消息对象
- message.setFrom(new InternetAddress(fromMail));//设置发件人的地址
- message.setRecipient(Message.RecipientType.TO, new InternetAddress(toMail));//设置收件人,并设置其接收类型为TO
- message.setSubject(mailTitle);//设置标题
- //设置信件内容
- // message.setText(mailContent); //发送 纯文本 邮件 todo
- message.setContent(mailContent, "text/html;charset=gbk"); //发送HTML邮件,内容样式比较丰富
- message.setSentDate(new Date());//设置发信时间
- message.saveChanges();//存储邮件信息
- //发送邮件
- // Transport transport = session.getTransport("smtp");
- Transport transport = session.getTransport();
- transport.connect(user, password);
- transport.sendMessage(message, message.getAllRecipients());//发送邮件,其中第二个参数是所有已设好的收件人地址
- transport.close();
- }
- public static void main(String[] args) throws Exception {
- sendMail("用户名@163.com", "用户", "密码",
- "[email protected]",
- "Java Mail 测试邮件",
- "<a>html 元素</a>:<b>邮件内容</b>");
- }
- }
以上来源:http://blog.csdn.net/conquer0715/article/details/44831851
另:结合以上可以实现一个Email的工具
代码如下:
import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.SendFailedException; 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; import org.apache.log4j.Logger; public class EmailHelper { private final static String default_charset = "UTF-8"; public static enum EncryptionTypes { Default, TLS, SSL; public static EncryptionTypes parseValue(int number){ switch(number){ case 2: return TLS; case 3: return SSL; default: return Default; } } public static EncryptionTypes parseValue(String str){ switch(str){ case "2": return TLS; case "3": return SSL; default: return Default; } } } private static Logger logger = Logger.getLogger(EmailHelper.class); private String mail_host = ""; private int mail_port = 25; private EncryptionTypes encryptionType = EncryptionTypes.Default; private String mail_host_account = ""; private String mail_host_password = ""; private boolean isHtml = false; private boolean isAuth = true; public EmailHelper(String mail_host, int mail_port, EncryptionTypes encryptionType, String account, String password, boolean isHtml) { this.mail_host = mail_host; this.mail_port = mail_port; this.encryptionType = encryptionType; this.mail_host_account = account; this.mail_host_password = password; this.isHtml = isHtml; } public void sendEmail(String senderAddress, String senderName, String receiverAddress, String sub, String msg) throws Exception { String[] address = receiverAddress.split(";"); List<String> recipients = new ArrayList<String>(); for (int i = 0; i < address.length; i++) { if (address[i].trim().length() > 0) { recipients.add(address[i]); } } this.sendEmail(senderAddress, senderName, recipients, sub, msg); } public void sendEmail(String senderAddress, String senderName, List<String> recipients, String sub, String msg) throws SendFailedException { logger.debug("mail subject=" + sub + ", mail_port=" + this.mail_port + ", encryptionType=" + this.encryptionType + ", auth=" + isAuth + ", mail_host_account=" + this.mail_host_account + ", mail_host_password=" + this.mail_host_password); Transport transport = null; try { Properties props = this.getProperties(); Session session = this.getSession(props); MimeMessage message = new MimeMessage(session); if (this.getDefaultIsHtml()) { message.addHeader("Content-type", "text/html"); } else { message.addHeader("Content-type", "text/plain"); } message.setSubject(sub, default_charset); message.setFrom(new InternetAddress(senderAddress, senderName)); for (Iterator<String> it = recipients.iterator(); it.hasNext();) { String email = (String) it.next(); message.addRecipients(Message.RecipientType.TO, email); } Multipart mp = new MimeMultipart(); MimeBodyPart contentPart = new MimeBodyPart(); if (this.getDefaultIsHtml()) { contentPart.setContent( "<meta http-equiv=Content-Type content=text/html; charset=" + default_charset + ">" + msg, "text/html;charset=" + default_charset); } else { contentPart.setText(msg, default_charset); } mp.addBodyPart(contentPart); message.setContent(mp); message.setSentDate(new Date()); if (this.getDefaultEncryptionType() == EncryptionTypes.SSL) { Transport.send(message); } else { transport = session.getTransport("smtp"); transport.connect(this.mail_host, this.mail_port, this.mail_host_account, this.mail_host_password); transport.sendMessage(message, message.getAllRecipients()); } logger.debug("Send email successfully by " + this.getDefaultEncryptionType()); } catch (Exception e) { logger.error("send mail error", e); } finally { if (transport != null) { try { transport.close(); } catch (Exception ex) { } } } } private Properties getProperties() { Properties props = System.getProperties(); EncryptionTypes defaultEncryptionType = this.getDefaultEncryptionType(); //do not need to authenticate smtp account if the user name and password are not set if(this.mail_host_account == null || "".equals(this.mail_host_account) || this.mail_host_password == null || "".equals(this.mail_host_password)){ isAuth = false; props.put("mail.smtp.auth", "false"); } else { props.put("mail.smtp.auth", "true"); } props.put("mail.smtp.host", this.mail_host); if (defaultEncryptionType == EncryptionTypes.TLS) { props.put("mail.smtp.starttls.enable", "true"); } else if (defaultEncryptionType == EncryptionTypes.SSL) { props.put("mail.smtp.socketFactory.port", this.mail_port); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.debug", "true"); props.put("mail.smtp.port", this.mail_port); } return props; } private Session getSession(Properties props) { Session session = null; if (this.getDefaultEncryptionType() == EncryptionTypes.TLS) { session = Session.getInstance(props); } else if (this.getDefaultEncryptionType() == EncryptionTypes.SSL) { session = Session.getInstance(props, new SMTPAuthenticator(this.mail_host_account, this.mail_host_password)); } else { session = Session.getDefaultInstance(props); } return session; } private boolean getDefaultIsHtml() { boolean rst = this.isHtml; return rst; } private class SMTPAuthenticator extends Authenticator { String user; String password; public SMTPAuthenticator(String user, String password) { this.user = user; this.password = password; } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(this.user, this.password); } } private EncryptionTypes getDefaultEncryptionType() { EncryptionTypes rst = this.encryptionType; if (this.encryptionType == EncryptionTypes.Default) { if (this.mail_port == 465) { rst = EncryptionTypes.SSL; } else if (this.mail_port == 587) { rst = EncryptionTypes.TLS; } } return rst; } }