javax.mail 发送邮件 java

在下载使用javax.mail的jar包时候,注意:

有的jar没有包含sun的实现,只包含了api,这类jar名称通常为javax.mail-api-x.x.x.jar,在使用smtp协议发邮件过程中会报错:

 

[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. java.lang.ClassNotFoundException: com.sun.mail.util.MailLogger  

另一种jar是包含了sun的实现的,名称通常为javax.mail-x.x.x.jar,使用smtp协议发邮件正常!

 

示例代码:

  1. package test.mail;  
  2.   
  3. import javax.mail.Message;  
  4. import javax.mail.Session;  
  5. import javax.mail.Transport;  
  6. import javax.mail.internet.InternetAddress;  
  7. import javax.mail.internet.MimeMessage;  
  8. import java.util.Date;  
  9. import java.util.Properties;  
  10.   
  11. public class TestMail {  
  12.     public static void sendMail(String fromMail, String user, String password,  
  13.                                 String toMail,  
  14.                                 String mailTitle,  
  15.                                 String mailContent) throws Exception {  
  16.         Properties props = new Properties(); //可以加载一个配置文件  
  17.         // 使用smtp:简单邮件传输协议  
  18.         props.put("mail.smtp.host""smtp.163.com");//存储发送邮件服务器的信息  
  19.         props.put("mail.smtp.auth""true");//同时通过验证  
  20.   
  21.         Session session = Session.getInstance(props);//根据属性新建一个邮件会话  
  22. //        session.setDebug(true); //有他会打印一些调试信息。  
  23.   
  24.         MimeMessage message = new MimeMessage(session);//由邮件会话新建一个消息对象  
  25.         message.setFrom(new InternetAddress(fromMail));//设置发件人的地址  
  26.         message.setRecipient(Message.RecipientType.TO, new InternetAddress(toMail));//设置收件人,并设置其接收类型为TO  
  27.         message.setSubject(mailTitle);//设置标题  
  28.         //设置信件内容  
  29. //        message.setText(mailContent); //发送 纯文本 邮件 todo  
  30.         message.setContent(mailContent, "text/html;charset=gbk"); //发送HTML邮件,内容样式比较丰富  
  31.         message.setSentDate(new Date());//设置发信时间  
  32.         message.saveChanges();//存储邮件信息  
  33.   
  34.         //发送邮件  
  35. //        Transport transport = session.getTransport("smtp");  
  36.         Transport transport = session.getTransport();  
  37.         transport.connect(user, password);  
  38.         transport.sendMessage(message, message.getAllRecipients());//发送邮件,其中第二个参数是所有已设好的收件人地址  
  39.         transport.close();  
  40.     }  
  41.   
  42.     public static void main(String[] args) throws Exception {  
  43.         sendMail("用户名@163.com""用户""密码",  
  44.                 "[email protected]",  
  45.                 "Java Mail 测试邮件",  
  46.                 "<a>html 元素</a>:<b>邮件内容</b>");  
  47.     }  
  48. }  

以上来源: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;
	}
}

 

猜你喜欢

转载自1960370817.iteye.com/blog/2372370