javamail邮件验证

方法调用:

User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        String userjson = UtilJson.toJson(user);
        String weburl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath();// 项目根路径
        weburl = weburl + "/ponal/active?userjson=" + userjson;
        try {
            UtilMail.sendMail(username, email, weburl);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

工具类:

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;

public class UtilMail {

    private static final String from = "[email protected]"; // 发件人邮箱地址
    private static final String user = "[email protected]"; // 发件人称号,同邮箱地址
    private static final String password = "XXXXXX"; // 发件人邮箱客户端授权码

    public static void sendMail(String username, String email, String weburl) throws MessagingException {
        Properties prop = new Properties();
        // prop.put("mail.host", "smtp.qq.com");// 指定邮件服务器,默认端口 25
        prop.put("mail.host", "smtp.163.com");
        prop.put("mail.transport.protocol", "smtp");
        prop.put("mail.smtp.auth", true);

        Session session = Session.getInstance(prop);

        Transport ts = session.getTransport();
        ts.connect(from, password);
        Message msg = createSimpleMail(session, email, username, weburl);
        ts.sendMessage(msg, msg.getAllRecipients());

    }

    private static MimeMessage createSimpleMail(Session session, String email, String username, String weburl)
            throws AddressException, MessagingException {
        // 创建邮件对象
        MimeMessage mm = new MimeMessage(session);
        // 设置发件人
        mm.setFrom(new InternetAddress(from));
        // 设置收件人
        mm.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
        // 设置抄送人
        // mm.setRecipient(Message.RecipientType.CC, new
        // InternetAddress("用户名@163.com"));
        mm.setSubject(username + ",欢迎注册个人简历网,请点击链接激活账号");
        StringBuilder sbd = new StringBuilder();
        sbd.append(username + "
欢迎!请确认此邮件地址以激活您的账号.
"
); sbd.append("); sbd.append(">立即激活
"
); sbd.append("或者点击下面链接:
"
); sbd.append(weburl + "
"
); sbd.append("这是一封自动发送的邮件;如果您并未要求但收到这封信件,您不需要进行任何操作。"); mm.setContent(sbd.toString(), "text/html;charset=utf-8"); return mm; } }

你可能感兴趣的:(其他)