码迷,mamicode.com
首页 > 编程语言 > 详细

Java使用javax.mail.jar发送邮件

时间:2014-06-07 16:16:46      阅读:277      评论:0      收藏:0      [点我收藏+]

标签:javax.mail.jar   java发送邮件   邮箱   面向对象   验证码   

由于Java在开发网页上占有绝大优势,所以作为web端的领军人物,譬如发送短信和发送邮件这些就成了必然,网络安全一再安全我们需要把账号的安全级别提到更高!因此这些对于开发人员也就成了必须掌握的技能!我一直都觉得作为开发人员,不怕在开发的过程中遇到多少难题,而是有没有去解决它的勇气和决心,这里多学习就成为了关键,成为了一个程序猿发展的重中之重!好啦,闲话就说到这里,来点实际的!

当一个开发人员工作到一定程度后,面向对象的思维就会一直在他的老子里围绕!所以我们先把邮件的常量类、实体类以及工具类等等先该封装的封装,该继承的继承!代码来了,睁大眼睛:

/**
 * @Description: 
 *
 * @Title: SimpleMail.java
 * @Package com.joyce.bean
 * @Copyright: Copyright (c) 2014
 *
 * @author Comsys-LZP
 * @date 2014-5-28 上午09:06:51
 * @version V2.0
 */
package com.joyce.mail.bean;

/**
 * @Description:邮件信息类
 * 
 * @ClassName: SimpleMail
 * @Copyright: Copyright (c) 2014
 * 
 * @author Comsys-LZP
 * @date 2014-5-28 上午09:06:51
 * @version V2.0
 */
public class Mail {
	/**
	 * 主题
	 */
	private String subject;
	/**
	 * 内容
	 */
	private String content;

	/**
	 * @return the subject
	 */
	public String getSubject() {
		return subject;
	}

	/**
	 * @param subject
	 *            the subject to set
	 */
	public void setSubject(String subject) {
		this.subject = subject;
	}

	/**
	 * @return the content
	 */
	public String getContent() {
		return content;
	}

	/**
	 * @param content
	 *            the content to set
	 */
	public void setContent(String content) {
		this.content = content;
	}
}

上面大家看到的就是发送邮件一般必不可少的邮件标题和邮件内容,作为在邮件使用广泛的那就免不了封装起来了,好啦,接下来咱们看邮箱的登录类:
/**
 * @Description: 
 *
 * @Title: MailAuthenticator.java
 * @Package com.joyce.bean
 * @Copyright: Copyright (c) 2014
 *
 * @author Comsys-LZP
 * @date 2014-5-28 上午08:59:11
 * @version V2.0
 */
package com.joyce.mail.bean;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

/**
 * @Description: 邮箱登录类
 *
 * @ClassName: MailAuthenticator
 * @Copyright: Copyright (c) 2014
 *
 * @author Comsys-LZP
 * @date 2014-5-28 上午08:59:11
 * @version V2.0
 */
public class MailAuthenticator extends Authenticator {
	/**
     * 用户名(登录邮箱)
     */
    private String username;
    
    /**
     * 密码
     */
    private String password;

	/**
	 * @return the username
	 */
	public String getUsername() {
		return username;
	}

	/**
	 * @param username the username to set
	 */
	public void setUsername(String username) {
		this.username = username;
	}

	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * @param password the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * @param username
	 * @param password
	 */
	public MailAuthenticator(String username, String password) {
		this.username = username;
		this.password = password;
	}
	
	@Override
	protected PasswordAuthentication getPasswordAuthentication() {
	    return new PasswordAuthentication(username, password);
    }
}

这时候我们需要的常量类就应该进来了
package com.joyce.mail.bean;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description: 邮件发送常量类
 *
 * @ClassName: MailConstant
 * @Copyright: Copyright (c) 2014
 *
 * @author Comsys-LZP
 * @date 2014-5-28 上午11:01:16
 * @version V2.0
 */
public class MailConstant {
	public static final String MAIL_USER = "luo201227@163.com"; 
	public static final String MAIL_PWD = "*****";
	public static final boolean MAIL_IFDEBUG = true;
	public static final String MAIL_CONTENT_CHARSET = "text/html;charset=utf-8"; 
	public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 E");
	public static final String MAIL_TITLE = "*********账号激活码" + sdf.format(new Date());//邮件标题
	public static String getMailContent(String content){
		StringBuffer sb = new StringBuffer();
		sb.append("<div style='width:1024px;height:auto;margin:0px auto;background-color:#66CCFF;font-size:14px;font-family:微软雅黑;border-radius:5px;padding:5px;'><center><h1>");
		sb.append("</h1></center><div style='margin-left:20px;margin-bottom:10px;'><b>尊敬的用户,您好!</b><br/><br/>");
		sb.append("    <b></b>"+content);		
		sb.append("</div></div>");
		return sb.toString();
	}
}

关键来了,看看发送邮件的关键部分吧
/**
 * @Description: 
 *
 * @Title: MailSender.java
 * @Package com.joyce.service.impl
 * @Copyright: Copyright (c) 2014
 *
 * @author Comsys-LZP
 * @date 2014-5-28 上午09:03:08
 * @version V2.0
 */
package com.joyce.mail.main;

import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.joyce.mail.bean.MailConstant;
import com.joyce.mail.bean.Mail;
import com.joyce.mail.bean.MailAuthenticator;

/**
 * @Description:邮件发送类
 * 
 * @ClassName: MailSender
 * @Copyright: Copyright (c) 2014
 * 
 * @author Comsys-LZP
 * @date 2014-5-28 上午09:03:08
 * @version V2.0
 */
public class MailSender {
	/**
	 * 发送邮件的props文件
	 */
	private final transient Properties props = new Properties();
	/**
	 * 邮件服务器登录验证
	 */
	private transient MailAuthenticator authenticator;

	/**
	 * 邮箱session
	 */
	private transient Session session;

	/**
	 * 初始化邮件发送器
	 * 
	 * @param smtpHostName
	 *            SMTP邮件服务器地址
	 * @param username
	 *            发送邮件的用户名(地址)
	 * @param password
	 *            发送邮件的密码
	 */
	public MailSender(final String smtpHostName, final String username,
			final String password) {
		init(username, password, smtpHostName);
	}

	/**
	 * 初始化邮件发送器
	 * 
	 * @param username
	 *            发送邮件的用户名(地址),并以此解析SMTP服务器地址
	 * @param password
	 *            发送邮件的密码
	 */
	public MailSender(final String username, final String password) {
		// 通过邮箱地址解析出smtp服务器,对大多数邮箱都管用
		final String smtpHostName = "smtp." + username.split("@")[1];
		init(username, password, smtpHostName);

	}

	/**
	 * @Description: 初始化
	 * 
	 * @param username
	 *            发送邮件的用户名(地址)
	 * @param password
	 *            密码
	 * @param smtpHostName
	 *            SMTP主机地址
	 * 
	 * @Title: MailSender.java
	 * @Copyright: Copyright (c) 2014
	 * 
	 * @author Comsys-LZP
	 * @date 2014-5-28 上午09:18:31
	 * @version V2.0
	 */
	private void init(String username, String password, String smtpHostName) {
		// 初始化props
		props.put("mail.smtp.host", smtpHostName);
		props.put("mail.smtp.auth", "true");
		// 验证
		authenticator = new MailAuthenticator(username, password);
		// 创建session
		session = Session.getInstance(props,authenticator);
		// 打印一些调试信息
		session.setDebug(MailConstant.MAIL_IFDEBUG);
	}

	/**
	 * @Description: 发送邮件
	 * 
	 * @param recipient
	 *            收件人邮箱地址
	 * @param subject
	 *            邮件主题
	 * @param content
	 *            邮件内容
	 * @throws AddressException
	 * @throws MessagingException
	 * 
	 * @Title: MailSender.java
	 * @Copyright: Copyright (c) 2014
	 * 
	 * @author Comsys-LZP
	 * @date 2014-5-28 上午09:19:16
	 * @version V2.0
	 */
	public void send(String recipient, String subject, Object content)
			throws AddressException, MessagingException {
		// 创建mime类型邮件
		final MimeMessage message = new MimeMessage(session);
		// 设置发信人
		message.setFrom(new InternetAddress(authenticator.getUsername()));
		// 设置收件人
		message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
		// 设置主题
		message.setSubject(subject);
		// 设置邮件内容
		message.setContent(content.toString(), MailConstant.MAIL_CONTENT_CHARSET);
		// 设置发信时间
		message.setSentDate(new Date());
		// 存储邮件信息
		message.saveChanges();
		// 发送邮件
		Transport.send(message);
	}

	/**
	 * @Description: 群发邮件
	 * 
	 * @param recipients
	 *            收件人们
	 * @param subject
	 *            主题
	 * @param content
	 *            内容
	 * @throws AddressException
	 * @throws MessagingException
	 * 
	 * @Title: MailSender.java
	 * @Copyright: Copyright (c) 2014
	 * 
	 * @author Comsys-LZP
	 * @date 2014-5-28 上午09:20:24
	 * @version V2.0
	 */
	public void send(List<String> recipients, String subject, Object content)
			throws AddressException, MessagingException {
		// 创建mime类型邮件
		final MimeMessage message = new MimeMessage(session);
		// 设置发信人
		message.setFrom(new InternetAddress(authenticator.getUsername()));
		// 设置收件人们
		final int num = recipients.size();
		InternetAddress[] addresses = new InternetAddress[num];
		for (int i = 0; i < num; i++) {
			addresses[i] = new InternetAddress(recipients.get(i));
		}
		message.setRecipients(Message.RecipientType.TO, addresses);
		// 设置主题
		message.setSubject(subject);
		// 设置邮件内容
		message.setContent(content.toString(),  MailConstant.MAIL_CONTENT_CHARSET);
		// 设置发信时间
		message.setSentDate(new Date());
		// 存储邮件信息
		message.saveChanges();
		// 发送邮件
		Transport.send(message);
	}

	/**
	 * @Description: 发送邮件
	 * 
	 * @param recipient
	 *            收件人邮箱地址
	 * @param mail
	 *            邮件对象
	 * @throws AddressException
	 * @throws MessagingException
	 * 
	 * @Title: MailSender.java
	 * @Copyright: Copyright (c) 2014
	 * 
	 * @author Comsys-LZP
	 * @date 2014-5-28 上午09:20:54
	 * @version V2.0
	 */
	public void send(String recipient, Mail mail)
			throws AddressException, MessagingException {
		send(recipient, mail.getSubject(), mail.getContent());
	}

	/**
	 * @Description: 群发邮件
	 * 
	 * @param recipients
	 *            收件人们
	 * @param mail
	 *            邮件对象
	 * @throws AddressException
	 * @throws MessagingException
	 * 
	 * @Title: MailSender.java
	 * @Copyright: Copyright (c) 2014
	 * 
	 * @author Comsys-LZP
	 * @date 2014-5-28 上午09:21:19
	 * @version V2.0
	 */
	public void send(List<String> recipients, Mail mail)
			throws AddressException, MessagingException {
		send(recipients, mail.getSubject(), mail.getContent());
	}
}

发送邮件的就在这里了!所有关键代码已完成,开始测试类
/**
 * @Description: 
 *
 * @Title: MailTest.java
 * @Package com.joyce.test
 * @Copyright: Copyright (c) 2014
 *
 * @author Comsys-LZP
 * @date 2014-5-28 上午09:07:52
 * @version V2.0
 */
package com.joyce.mail.test;

import com.joyce.mail.bean.Mail;
import com.joyce.mail.bean.MailConstant;
import com.joyce.mail.main.MailSender;
import com.joyce.mail.util.RandomCodeUtil;

/**
 * @Description: 发送邮件测试类
 *
 * @ClassName: MailTest
 * @Copyright: Copyright (c) 2014
 *
 * @author Comsys-LZP
 * @date 2014-5-28 上午09:07:52
 * @version V2.0
 */
public class MailTest {
	public static void main(String[] args) {
		try {
			MailSender mail = new MailSender(MailConstant.MAIL_USER, MailConstant.MAIL_PWD);
			Mail content = new Mail();
			content.setSubject(MailConstant.MAIL_TITLE);
			content.setContent(MailConstant.getMailContent("欢迎使用******产品,您的激活码为:<span style='color:green;'>"+RandomCodeUtil.randomCode(6)+"</span>,仅本次生效!"));
			mail.send("luo201227@163.com", content);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

在网页上的激活码或者验证码这类的就不用多说了吧
/**
 * @Description: 
 *
 * @Title: RandomCodeUtil.java
 * @Package com.joyce.mail.util
 * @Copyright: Copyright (c) 2014
 *
 * @author Comsys-LZP
 * @date 2014-5-28 上午11:07:34
 * @version V2.0
 */
package com.joyce.mail.util;


/**
 * @Description: 随机码工具类
 * 
 * @ClassName: RandomCodeUtil
 * @Copyright: Copyright (c) 2014
 * 
 * @author Comsys-LZP
 * @date 2014-5-28 上午11:07:34
 * @version V2.0
 */
public class RandomCodeUtil {
	/**
	 * 随机码集合
	 */
	private static final String[] randCode = { "0", "1", "2", "3", "4", "5", "6",
			"7", "8", "9", "q", "w", "e", "r", "t", "y", "u", "i", "o", "p",
			"a", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v",
			"b", "n", "m" };
	
	/**
	 * @Description: 产生指定长度的随机码
	 *
	 * @param codeLength
	 * @return
	 *
	 * @Title: RandomCodeUtil.java
	 * @Copyright: Copyright (c) 2014
	 *
	 * @author Comsys-LZP
	 * @date 2014-5-28 上午11:11:55
	 * @version V2.0
	 */
	public static String randomCode(Integer codeLength) throws Exception {
		try {
			StringBuffer code = new StringBuffer();
			if(null == codeLength || 0 == codeLength){
				codeLength = 4;
			}
			for (int i = 0; i < codeLength; i++) {
				code.append(randCode[(int)Math.floor(Math.random() * 36)]);
			}
			return code.toString();
		} catch (Exception e) {
			throw new RuntimeException("Random Code Error");
		}
	}
	
	/**
	 * @Description: 生成长度为4的随机码
	 *
	 * @return
	 * @throws Exception
	 *
	 * @Title: RandomCodeUtil.java
	 * @Copyright: Copyright (c) 2014
	 *
	 * @author Comsys-LZP
	 * @date 2014-5-28 下午01:19:33
	 * @version V2.0
	 */
	public static String randomCode() throws Exception{
		return randomCode(null);
	}
}

Ok,利用javax.mail.jar发送邮件就大功告成了!是不是很easy呢!完整的demo资源;下载地址: http://download.csdn.net/download/luo201227/7446279

Java使用javax.mail.jar发送邮件,布布扣,bubuko.com

Java使用javax.mail.jar发送邮件

标签:javax.mail.jar   java发送邮件   邮箱   面向对象   验证码   

原文地址:http://blog.csdn.net/luo201227/article/details/28425283

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!