Spark/Utils-實現Spark的內置離線監控(細粒度任務的監控和異常報警)---1.實現郵件發送模塊的開發

import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * Created by angel
 */
public class MailUtil {
    /**
     * args[0]:接收人郵箱,以‘,’連接
     * args[1]:郵件標題
     * args[2]:郵件內容
     * @param args
     * @throws Exception
     */
    public static void sendMail(Properties props, String[] args) throws Exception{

        if(args.length != 3){
            System.out.println("請輸入三個參數:\nargs[0]:接收人郵箱,以‘,’連接;\nargs[1]:郵件標題;\nargs[2]:郵件內容。");
            return;
        }
        String reciveEmails = args[0];
        String title = args[1];
        String content = args[2];

        // 構建授權信息,用於進行SMTP進行身份驗證
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用戶名、密碼
                String userName = "自己的163郵箱賬號";
                String password = "SMTP授權服務碼"; //申請方式看文末
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用環境屬性和授權信息,創建郵件會話
        Session mailSession = Session.getInstance(props, authenticator);
        // 創建郵件消息
        MimeMessage message = new MimeMessage(mailSession);
        // 設置發件人
        InternetAddress form = new InternetAddress(
                "[email protected]");
        message.setFrom(form);
        // 設置收件人  "[email protected],[email protected],[email protected]"
        InternetAddress[] internetAddressTo = new InternetAddress().parse(reciveEmails);
        message.setRecipients(RecipientType.TO, internetAddressTo);

        // 設置郵件標題
        message.setSubject(title);
        // 設置郵件的內容體
        message.setContent(content, "text/html;charset=UTF-8");
        // 發送郵件
        Transport.send(message);
    }
	//做一個測試
    public static void main(String[] args) {
    	//prop需要三個設置
        Properties properties = new Properties();
        properties.setProperty("mail.host","smtp.163.com");//郵件主機
        properties.setProperty("mail.transport.protocol", "smtp");//發送郵件使用smtp協議
        properties.setProperty("mail.smtp.auth","true");//是否smtp認證
        String[] str = new String[]{"接收郵件的用戶郵箱號(可以是非163的)", "spark任務監控" , "測試=============="};
        try {
            MailUtil.sendMail(properties , str);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

開啓SMTP 他回給你一個授權密碼的彈出框,只會出現一次,切記!!!要保存一下在關閉
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章