1. 程式人生 > 其它 >一個Java傳送郵件的案例

一個Java傳送郵件的案例

經常有些要傳送郵件的需求,但是去網上拷程式碼老是拷不到能直接執行的,還經常要去以前的專案裡面拷,今天直接發出來算了,免得每次都要去別的專案拷。

(只支援傳送簡單的文字檔案,發附件的稍微複雜一丟丟,這裡就不貼出來了)

依賴:

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.5.0-b01</version>
</dependency>

原始碼:

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

public class SendIdentifyingCode {

    public SendIdentifyingCode(String address, String content) {
        Properties prop = new Properties();
        prop.setProperty("mail.host", "smtp.qq.com");
        prop.setProperty("mail.transport.protocol", "smtp");
        prop.setProperty("mail.smtp.auth", "true");
        //用465埠
        prop.setProperty("mail.smtp.port", "465");
        prop.setProperty("mail.smtp.ssl.enable", "true");

        Session session = Session.getInstance(prop);
        session.setDebug(true);
        Transport ts = null;
        try {
            ts = session.getTransport();
            //下面這行自己用自己的噢,最後那個引數在我下面那個圖裡面開啟點兩下就可以找到了
            ts.connect("smtp.qq.com", "[email protected]", "xxxxxxxxxxx");
            Message message = createSimpleMail(session, address, content);
            ts.sendMessage(message, message.getAllRecipients());
        } catch (MessagingException e) {
            e.printStackTrace();
        } finally {
            try {
                assert ts != null;
                ts.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
    }

    private MimeMessage createSimpleMail(Session session, String address, String content) throws MessagingException {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("[email protected]"));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(address));
        message.setSubject("FaceProcessor驗證訊息");//郵件標題
        message.setContent(content, "text/html;charset=UTF-8");//支援html格式
        return message;
    }

}

這邊用的QQ郵箱

埠報錯的話就用25,但是雲伺服器不讓你用25埠,465埠是用的SSL,用這埠屁事比較多,jdk版本稍微高一點的話把SSL禁用了

解決方案https://blog.csdn.net/ooblack/article/details/119300423

然後要是能用25的話儘量用25得了,但是雲伺服器去申請25解封通過率不高

貼一個各個郵箱對應的埠

https://www.cnblogs.com/ni-huang-feng-wu/p/14773917.html

SpringBoot又把這玩意又封裝了一次,如果是Spring忠實粉絲的話可以去用SpringBoot的

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-mail -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
    <version>2.5.6</version>
</dependency>

接下來怎麼寫自行百度。