java mail 注册邮箱的实现

核心代码:

package cn.itcast.shop.utils;

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

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
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;

/**
 * 邮件发送工具类
 * 
 * @author admin
 *
 */
public class MailUtils {
	// --------------参数---------------------
	public static final String FROM = "[email protected]";// 发件人的email
	public static final String PWD = "*******";// 发件人密码--邮箱smtp授权码
	public static final String URL = "http://192.168.32.1:8080/shop";// 项目主页
	public static final String TITLE = "*********";
	public static final String HOST = "smtp.163.com";
	public static final String SMTP = "smtp";

	/**
	 * 发送邮件方法
	 * 
	 * @param to:收件人邮箱
	 * @param code:激活码
	 */
	public static void sendMail(String to, String code) {
		/**
		 * 1.获得一个session对象 2.创建一个代表邮件的对象Message 3.创建发送邮件Transport
		 */
		//发送邮件内容
		String context = "

官方激活邮件,点击下面链接完成激活操作!

" + URL + "/user_active.action?code=" + code + "

"; // 1.获得连接对象Session Properties props = new Properties(); // 设置发送主机属性 props.setProperty("mail.host", HOST);//存储发送邮件服务器的信息 props.setProperty("mail.smtp.auth", "true");//同时通过验证 Session session = Session.getInstance(props);//根据属性新建一个邮件会话 // 2.创建邮件对象Message Message message = new MimeMessage(session); // 设置发件人: try { message.setFrom(new InternetAddress(FROM));//设置发件人的地址 // 设置收件人://抄送 CC 密送BCC message.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 设置标题 message.setSubject(TITLE); // 设置邮件正文(正文内容,格式) message.setContent(context, "text/html;charset=UTF-8"); //设置发信时间 message.setSentDate(new Date()); //存储邮件信息 message.saveChanges(); // 3.发送邮件 Transport transport = session.getTransport(SMTP); transport.connect(FROM,PWD); transport.sendMessage(message,message.getAllRecipients());//发送邮件,第二个参数是所有已经设好的收件人地址 transport.close(); } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } public static void main(String[] args) { sendMail("******@qq.com", "4545467454664"); System.out.println("发送邮件!"); } }

 

你可能感兴趣的:(Java后端)