【java工具類】發郵件工具類

【java工具類】發郵件工具類

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * 發郵件工具類
 */
public final class MailUtils {
    private static final String USER = ""; // 發件人稱號,同郵箱地址
    private static final String PASSWORD = ""; // 戶端授權碼

    /**
     *
     * @param to 收件人郵箱
     * @param text 郵件正文
     * @param title 標題
     */
    /* 發送驗證信息的郵件 */
    public static boolean sendMail(String to, String text, String title){
        try {
            final Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.host", "smtp.qq.com");

            // 發件人的賬號
            props.put("mail.user", USER);
            //發件人的密碼
            props.put("mail.password", PASSWORD);

            // 構建授權信息,用於進行SMTP進行身份驗證
            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    // 用戶名、密碼
                    String userName = props.getProperty("mail.user");
                    String password = props.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password);
                }
            };
            // 使用環境屬性和授權信息,創建郵件會話
            Session mailSession = Session.getInstance(props, authenticator);
            // 創建郵件消息
            MimeMessage message = new MimeMessage(mailSession);
            // 設置發件人
            String username = props.getProperty("mail.user");
            InternetAddress form = new InternetAddress(username);
            message.setFrom(form);

            // 設置收件人
            InternetAddress toAddress = new InternetAddress(to);
            message.setRecipient(Message.RecipientType.TO, toAddress);

            // 設置郵件標題
            message.setSubject(title);

            // 設置郵件的內容體
            message.setContent(text, "text/html;charset=UTF-8");
            // 發送郵件
            Transport.send(message);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    public static void main(String[] args) throws Exception { // 做測試用
        MailUtils.sendMail("郵箱地址","你好,這是一封測試郵件,無需回覆。","測試郵件");
        System.out.println("發送成功");
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章