發送激活碼到郵箱激活賬戶


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&code="+user.getCode()+"'>請點擊激活</a>";
   MailUtils.sendMail(user.getEmail(), emailMsg);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM