日本熟妇hd丰满老熟妇,中文字幕一区二区三区在线不卡 ,亚洲成片在线观看,免费女同在线一区二区

SMTP 之 Java 調(diào)用示例

本文介紹使用 Javamail 通過 SMTP 協(xié)議發(fā)信。

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>
<dependency>
    <groupId>javax.activation</groupId>
    <artifactId>activation</artifactId>
    <version>1.1.1</version>
</dependency>
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.6</version>
</dependency>

示例代碼:

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;
//import java.util.HashMap;
//import java.util.Base64;
//import com.google.gson.GsonBuilder;
//import javax.activation.DataHandler;
//import javax.activation.FileDataSource;
//import java.net.URL;
//import java.net.URLEncoder;
//import javax.activation.DataHandler;
//import javax.activation.URLDataSource;

public class SampleMail {
    protected static String genMessageID(String mailFrom) {
        // message-id 用于唯一地標(biāo)識每一封郵件,其格式需要遵循RFC 5322標(biāo)準(zhǔn),通常如 <uniquestring@example.com>,其中uniquestring是郵件服務(wù)器生成的唯一標(biāo)識,可能包含時間戳、隨機(jī)數(shù)等信息。
        String[] mailInfo = mailFrom.split("@");
        String domain = mailFrom;
        int index = mailInfo.length - 1;
        if (index >= 0) {
            domain = mailInfo[index];
        }
        UUID uuid = UUID.randomUUID();
        StringBuffer messageId = new StringBuffer();
        messageId.append('<').append(uuid.toString()).append('@').append(domain).append('>');
        return messageId.toString();
    }

    public static void main(String[] args) {
        // 配置發(fā)送郵件的環(huán)境屬性
        final Properties props = new Properties();

        // 表示SMTP發(fā)送郵件,需要進(jìn)行身份驗(yàn)證
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", "smtpdm.aliyun.com");
        //設(shè)置端口:
        props.put("mail.smtp.port", "80");//或"25", 如果使用ssl,則去掉使用80或25端口的配置,進(jìn)行如下配置:
        //加密方式:
        //props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        //props.put("mail.smtp.socketFactory.port", "465");
        //props.put("mail.smtp.port", "465");

        props.put("mail.smtp.from", "發(fā)信地址");    //mailfrom 參數(shù)
        props.put("mail.user", "發(fā)信地址");// 發(fā)件人的賬號(在控制臺創(chuàng)建的發(fā)信地址)
        props.put("mail.password", "SMTP密碼");// 發(fā)信地址的smtp密碼(在控制臺選擇發(fā)信地址進(jìn)行設(shè)置)
        //props.setProperty("mail.smtp.ssl.enable", "true");  //請配合465端口使用
        System.setProperty("mail.mime.splitlongparameters", "false");//用于解決附件名過長導(dǎo)致的顯示異常
        //props.put("mail.smtp.connectiontimeout", 1000);

        // 構(gòu)建授權(quán)信息,用于進(jìn)行SMTP進(jìn)行身份驗(yàn)證
        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);
            }
        };

        //使用環(huán)境屬性和授權(quán)信息,創(chuàng)建郵件會話
        Session mailSession = Session.getInstance(props, authenticator);
        //mailSession.setDebug(true);//開啟debug模式


        final String messageIDValue = genMessageID(props.getProperty("mail.user"));
        //創(chuàng)建郵件消息
        MimeMessage message = new MimeMessage(mailSession) {
            @Override
            protected void updateMessageID() throws MessagingException {
                //設(shè)置自定義Message-ID值
                setHeader("Message-ID", messageIDValue);//創(chuàng)建Message-ID
            }
        };

        try {
            // 設(shè)置發(fā)件人郵件地址和名稱。填寫控制臺配置的發(fā)信地址。和上面的mail.user保持一致。名稱用戶可以自定義填寫。
            InternetAddress from = new InternetAddress("發(fā)信地址", "發(fā)件人名稱");//from 參數(shù),可實(shí)現(xiàn)代發(fā),注意:代發(fā)容易被收信方拒信或進(jìn)入垃圾箱。
            message.setFrom(from);

            //可選。設(shè)置回信地址
            Address[] a = new Address[1];
            a[0] = new InternetAddress("收信地址");
            message.setReplyTo(a);

            // 設(shè)置收件人郵件地址
            InternetAddress to = new InternetAddress("收信地址");
            message.setRecipient(MimeMessage.RecipientType.TO, to);
            //如果同時發(fā)給多人,才將上面兩行替換為如下(因?yàn)椴糠质招畔到y(tǒng)的一些限制,盡量每次投遞給一個人;同時我們限制單次允許發(fā)送的人數(shù),具體參考規(guī)格清單):
            //InternetAddress[] adds = new InternetAddress[2];
            //adds[0] = new InternetAddress("收信地址");
            //adds[1] = new InternetAddress("收信地址");
            //message.setRecipients(Message.RecipientType.TO, adds);

            message.setSentDate(new Date()); //設(shè)置時間
            String ccUser = "抄送地址";
            // 設(shè)置多個抄送地址
            if (null != ccUser && !ccUser.isEmpty()) {
                @SuppressWarnings("static-access")
                InternetAddress[] internetAddressCC = new InternetAddress().parse(ccUser);
                message.setRecipients(Message.RecipientType.CC, internetAddressCC);
            }
            String bccUser = "密送地址";
            // 設(shè)置多個密送地址
            if (null != bccUser && !bccUser.isEmpty()) {
                @SuppressWarnings("static-access")
                InternetAddress[] internetAddressBCC = new InternetAddress().parse(bccUser);
                message.setRecipients(Message.RecipientType.BCC, internetAddressBCC);
            }
            //設(shè)置郵件標(biāo)題
            message.setSubject("測試主題");
            message.setContent("測試<br> 內(nèi)容", "text/html;charset=UTF-8");//html超文本;// "text/plain;charset=UTF-8" //純文本。

//            //若需要開啟郵件跟蹤服務(wù),請使用以下代碼設(shè)置跟蹤鏈接頭。前置條件和約束見文檔"如何開啟數(shù)據(jù)跟蹤功能?"
//            String tagName = "Test";
//            HashMap<String, String> trace = new HashMap<>();
//            //這里為字符串"1"
//            trace.put("OpenTrace", "1");      //打開郵件跟蹤
//            trace.put("LinkTrace", "1");     //點(diǎn)擊郵件里的URL跟蹤
//            trace.put("TagName", tagName);   //控制臺創(chuàng)建的標(biāo)簽tagname
//            String jsonTrace = new GsonBuilder().setPrettyPrinting().create().toJson(trace);
//            //System.out.println(jsonTrace);
//            String base64Trace = new String(Base64.getEncoder().encode(jsonTrace.getBytes()));
//            //設(shè)置跟蹤鏈接頭
//            message.addHeader("X-AliDM-Trace", base64Trace);
//            //郵件eml原文中的示例值:X-AliDM-Trace: eyJUYWdOYW1lIjoiVGVzdCIsIk9wZW5UcmFjZSI6IjEiLCJMaW5rVHJhY2UiOiIxIn0=

//發(fā)送附件和內(nèi)容:
//            BodyPart messageBodyPart = new MimeBodyPart();
//            //messageBodyPart.setText("消息<br>Text");//設(shè)置郵件的內(nèi)容,文本
//            messageBodyPart.setContent("測試<br> 內(nèi)容", "text/html;charset=UTF-8");// 純文本:"text/plain;charset=UTF-8" //設(shè)置郵件的內(nèi)容
//            //創(chuàng)建多重消息
//            Multipart multipart = new MimeMultipart();
//            //設(shè)置文本消息部分
//            multipart.addBodyPart(messageBodyPart);

//            //附件部分
//            //發(fā)送附件,總的郵件大小不超過15M,創(chuàng)建消息部分。
            //發(fā)送本地附件
//            String[] fileList = new String[2];
//            fileList[0] = "C:\\Users\\test1.txt";
//            fileList[1] = "C:\\Users\\test2.txt";
//            for (int index = 0; index < fileList.length; index++) {
//                MimeBodyPart mimeBodyPart = new MimeBodyPart();
//                //            //設(shè)置要發(fā)送附件的文件路徑
//                FileDataSource filesdata = new FileDataSource(fileList[index]);
//                mimeBodyPart.setDataHandler(new DataHandler(filesdata));
//                //處理附件名稱中文(附帶文件路徑)亂碼問題
//                mimeBodyPart.setFileName(MimeUtility.encodeWord("自定義附件名.xlsx"));
//                mimeBodyPart.addHeader("Content-Transfer-Encoding", "base64");
//                multipart.addBodyPart(mimeBodyPart);
//            }


            //發(fā)送URL附件
//            String[] fileList = new String[2];
//            fileList[0] = "https://example.oss-cn-shanghai.aliyuncs.com/xxxxxxxxxxx1.png";
//            fileList[1] = "https://example.oss-cn-shanghai.aliyuncs.com/xxxxxxxxxxx2.png";
//            for  (int index = 0; index < fileList.length; index++) {
//                String encode = URLEncoder.encode(fileList[index], "UTF-8");
//                MimeBodyPart mimeBodyPart = new MimeBodyPart();
//                mimeBodyPart.setDataHandler(new DataHandler(new URLDataSource(new URL(encode.replace("%3A",":").replace("%2F","/")))));
//                mimeBodyPart.setFileName(MimeUtility.encodeText("自定義附件名.xlsx"));
//                multipart.addBodyPart(mimeBodyPart);
//            }


//            //發(fā)送含有附件的完整消息
//            message.setContent(multipart);
//            // 發(fā)送附件代碼,結(jié)束

            // 發(fā)送郵件
            Transport.send(message);

        } catch (MessagingException e) {
            String err = e.getMessage();
            // 在這里處理message內(nèi)容, 格式是固定的
            System.out.println(err);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } //catch (MalformedURLException e) {
        //    e.printStackTrace();
        //}
    }
}