码迷,mamicode.com
首页 > 其他好文 > 详细

6.用户模块:邮件发送

时间:2015-04-12 22:49:18      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

package cn.xdy.shop.util;

import java.util.Properties;

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

public class MailUtil {

	/**
	 * 发送邮件的方法
	 * @param to 收件人
	 * @param code 激活码
	 */
	public static void sendMail(String to,String code){
		/**
		 * 1.获得一个session对象
		 * 2.创建一个代表邮件的对象message
		 * 3.发送邮件Transport
		 */
		//1.获得连接对象
		Properties props = new Properties();
		props.setProperty("mail.host", "smtp.126.com");
		props.put("mail.smtp.auth", "true"); 
		Session session = Session.getInstance(props, new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("x@126.com", "111");
			}
		});
		//2.创建邮件对象
		Message message = new MimeMessage(session);
		try {
			//设置发件人
			message.setFrom(new InternetAddress("x@126.com"));
			//设置收件人
			message.addRecipient(RecipientType.TO, new InternetAddress(to));
			//设置标题
			message.setSubject("来自星辰网上商城官方激活邮件");
			//设置邮件正文
			message.setContent(
					"<h1>星辰网上商城官方激活邮件!点击下面链接完成激活:</h1><br><h3><a href='http://127.0.0.1:8080/shop/user_active.action?code="
							+ code
							+ "'>http://127.0.0.1:8080/shop/user_active.action?code="
							+ code + "</a></h3>", "text/html;charset=utf-8");
			//3.发送邮件
			Transport.send(message);
		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		sendMail("123456@qq.com","21212");
	}
}

6.用户模块:邮件发送

标签:

原文地址:http://blog.csdn.net/xiongwt/article/details/45014305

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