开发中往往需要发送邮件给用户,提醒用户需要如何操作,如注册发送激活码,点击激活账户:邮件工具类如下:

package com.ceobai.utils;

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 MailUtils {

    public static void sendMail(String email, String emailMsg)
            throws AddressException, MessagingException {
        // 1.创建一个程序与邮件服务器会话对象 Session
        Properties props = new Properties();
        //设置发送的协议   *可能需要改的地方*
        props.setProperty("mail.transport.protocol", "SMTP");
        
        //设置发送邮件的服务器     *localhost需要根据实际情况更改,如163的为 smtp.163.com*
        props.setProperty("mail.host", "localhost");
        props.setProperty("mail.smtp.auth", "true");// 指定验证为true

        // 创建验证器
        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                //设置发送人的帐号和密码       *需要改的地方*
                return new PasswordAuthentication("root", "123");
            }
        };

        Session session = Session.getInstance(props, auth);

        // 2.创建一个Message,它相当于是邮件内容
        Message message = new MimeMessage(session);

        //设置发送者       *需要改的地方,如ceobaidu@163.com*
        message.setFrom(new InternetAddress("root@dege.com"));

        //设置发送方式与接收者(mail目的地)
        message.setRecipient(RecipientType.TO, new InternetAddress(email)); 

        //设置邮件主题    *根据实际情况添加主题*
        message.setSubject("来自德哥会所的激活邮件");
        // message.setText("这是一封激活邮件,请<a href='#'>点击</a>");

        //设置邮件内容  
        message.setContent(emailMsg, "text/html;charset=utf-8");

        // 3.创建 Transport用于将邮件发送
        Transport.send(message);
    }
}

调用该工具类的代码:

//发送邮件(email收件人地址)(emailMsg邮件的内容)(localhost网站的域名)
   String emailMsg = "欢迎来到德哥会所,<a href='http://localhost:8089/store_v2.0/userServlet?method=active&amp;code="+user.getCode()+"'>请点击激活</a>";
   MailUtils.sendMail(user.getEmail(), emailMsg);