java邮件工具类

该工具类用于向目标用户发送邮件:


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.URL;
import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
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.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.lang.StringUtils;

/*
 * @author: 杨楚杰
 * @date: 2013-8-6
 * @description: 用于发送邮件的工具类,在这个类中我们默认采用smtp.163.com的端口25来发送。
 * 				   如需修改,可调用setDefaultProperties方法来更改默认配置。
 * 
 */
public class MailUtils {
	//配置文件的路径名(注意路径的配置)
	private static final String configFilePath = "com/geoway/mail/mail.properties";
	// 发送邮件的服务器的IP和端口   
    private String mailServerHost;   
    private String mailServerPort;   
    // 邮件发送者的地址   
    private String fromAddress;   
    // 邮件接收者的地址   
    private String toAddress;   
    // 登陆邮件发送服务器的用户名和密码   
    private String userName;   
    private String password;   
    // 邮件主题   
    private String subject;   
    // 邮件的文本内容   
    private String content;       
    //Session
    private Session session;
    private Properties properties;
	/*
	 * description: 初始化邮件发送时的部分信息
	 */
	private void init(){
	    InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(configFilePath); 
	    Properties p = new Properties();   
	    try {   
	      p.load(inputStream);   
	     } catch (IOException e1) {   
	      e1.printStackTrace();   
	     }   
	   mailServerHost = p.getProperty("mailServerHost");
	   mailServerPort = p.getProperty("mailServerPort");
	   fromAddress = p.getProperty("fromAddress");
	   userName = p.getProperty("userName");
	   password = p.getProperty("password");
	   
	   properties = new Properties();   
	   properties.put("mail.smtp.host", this.mailServerHost);   
	   properties.put("mail.smtp.port", this.mailServerPort);   
	   properties.put("mail.smtp.auth", "true");   
	   session = Session.getDefaultInstance(properties);
	   session.setDebug(true); //设置为true后可以清楚的看到发送邮件的过程
	}
	
	/*
	 * description: 根据自己的需要来更改改工具类的默认配置
	 */
	public void setDefaultProperties(String mailServerHost, String mailServerPort, 
			String fromAddress, String userName, String password){
		
		Properties p = new Properties();   
		p.setProperty("mailServerHost", mailServerHost);  
		p.setProperty("mailServerPort", mailServerPort);
		p.setProperty("fromAddress", fromAddress);
		p.setProperty("userName", userName);
		p.setProperty("password", password);
		FileOutputStream fos = null;
		try {
			//注意路径的设置问题
			fos = new FileOutputStream("src/com/geoway/mail/mail.properties");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		try {
			p.store(fos, "edit by andyyang");
			fos.close();
			System.out.println("修改成功!");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/*
	 * description: 设置邮件发送地址,主题,内容后发送邮件
	 */
	public void sendMail(String toAddress, String subject, String content){
		this.init();
		// 根据session创建一个邮件消息   
	    Message mailMessage = new MimeMessage(session); 
	    // 创建邮件发送者地址   
		try {
			  Address from = new InternetAddress(fromAddress);
			  // 设置邮件消息的发送者   
		      mailMessage.setFrom(from);   
		      // 创建邮件的接收者地址,并设置到邮件消息中   
		      Address to = new InternetAddress(toAddress);   
		      // Message.RecipientType.TO属性表示接收者的类型为TO   
		      mailMessage.addRecipient(Message.RecipientType.TO,to);   
		      // 设置邮件消息的主题   
		      mailMessage.setSubject(subject);   
		      // 设置邮件消息发送的时间   
		      mailMessage.setSentDate(new Date());   
		      // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象   
		      Multipart mainPart = new MimeMultipart();   
		      // 创建一个包含HTML内容的MimeBodyPart   
		      BodyPart html = new MimeBodyPart();   
		      // 设置HTML内容   
		      html.setContent(content, "text/html; charset=utf-8");   
		      mainPart.addBodyPart(html);   
		      // 将MiniMultipart对象设置为邮件内容   
		      mailMessage.setContent(mainPart);
		      mailMessage.saveChanges();
		      Transport transport = session.getTransport("smtp");
		      transport.connect(mailServerHost, userName, password);
		      transport.sendMessage(mailMessage, mailMessage.getAllRecipients());
		      transport.close();
		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		} 
	}
	
}
邮件服务器配置信息:

#edit by andyyang
mailServerPort=25
password=*********
mailServerHost=smtp.163.com
fromAddress=**********
userName=***********


/* * JCatalog Project */ package com.hexiang.utils; import java.util.List; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.Properties; import javax.mail.Session; import javax.mail.Transport; import javax.mail.Message; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.hexiang.exception.CatalogException; /** * Utility class to send email. * * @author <a href="380595305@qq.com">hexiang</a> */ public class EmailUtil { //the logger for this class private static Log logger = LogFactory.getLog("com.hexiang.util.EmailUtil"); /** * Send email to a single recipient. * * @param smtpHost the SMTP email server address * @param senderAddress the sender email address * @param senderName the sender name * @param receiverAddress the recipient email address * @param sub the subject of the email * @param msg the message content of the email */ public static void sendEmail(String smtpHost, String senderAddress, String senderName, String receiverAddress, String sub, String msg) throws CatalogException { List<String> recipients = new ArrayList<String>(); recipients.add(receiverAddress); sendEmail(smtpHost, senderAddress, senderName, recipients, sub, msg); } /** * Send email to a list of recipients. * * @param smtpHost the SMTP email server address * @param senderAddress the sender email address * @param senderName the sender name * @param recipients a list of receipients email addresses * @param sub the subject of the email * @param msg the message content of the email */ public static void sendEmail(String smtpHost, String senderAddress, String senderName, List<String> recipients, String sub, String msg) throws CatalogException { if (smtpHost == null) { String errMsg = "Could not send email: smtp host address is null"; logger.error(errMsg); throw new CatalogException(errMsg); } try { Properties props = System.getProperties(); props.put("mail.smtp.host", smtpHost); Session session = Session.getDefaultInstance(props, null ); MimeMessage message = new MimeMessage( session ); message.addHeader("Content-type", "text/plain"); message.setSubject(sub); 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); } message.setText(msg); message.setSentDate( new Date() ); Transport.send(message); } catch (Exception e) { String errorMsg = "Could not send email"; logger.error(errorMsg, e); throw new CatalogException("errorMsg", e); } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值