目錄
使用Java 發送電子郵件
首頁 Java java教程 我可以在沒有任何配置的情況下使用 Java 透過本機 SMTP 伺服器發送電子郵件嗎?

我可以在沒有任何配置的情況下使用 Java 透過本機 SMTP 伺服器發送電子郵件嗎?

Nov 11, 2024 am 08:17 AM

Can I send emails using Java with a localhost SMTP server without any configuration?

使用Java 發送電子郵件

問題:

由於連接原因,嘗試使用Java 發送電子郵件時發生錯誤本地主機SMTP問題

問題:

提供的程式碼可以用來傳送電子郵件嗎?

答案:

提供的使用 Java 發送電子郵件的程式碼(使用郵件伺服器的預設)可能無法在所有版本中工作案例。具體來說,本地主機 SMTP 伺服器預設情況下不太可能正常運作。

解決方案:

要使用 Java 可靠地發送電子郵件,請考慮使用第三方 SMTP 伺服器,例如如Google郵件。下面的代碼片段演示瞭如何使用Google 的API 和oAuth2 身份驗證通過Google 的SMTP 服務器發送電子郵件:

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.Message;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class GoogleMail {
    private static final GsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
    private static final HttpTransport HTTP_TRANSPORT;
    private static final File DATA_STORE_DIRECTORY = getGmailDataDirectory();

    static {
        try {
            HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        } catch (GeneralSecurityException | IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static Gmail getGmailService(Credential credential) throws IOException {
        return new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName("My Gmail App").build();
    }

    private static File getGmailDataDirectory() {
        return new File(org.yccheok.jstock.gui.Utils.getUserDataDirectory() + "authentication" + File.separator + "gmail");
    }

    public static void sendEmail(String to, String subject, String message) throws MessagingException, IOException {
        // Get the email account from saved credentials
        String email = loadEmail(DATA_STORE_DIRECTORY);
        if (email == null) {
            // If no credentials saved, request user authorization
            Pair<Pair<Credential, String>, Boolean> credentials = authorizeGmail();
            if (!credentials.second) {
                throw new RuntimeException("Failed to get credentials from user");
            }
            email = credentials.first.second;
            // Save the email address for future use
            saveEmail(DATA_STORE_DIRECTORY, email);
        }

        // Create a MIME message
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        MimeMessage emailMessage = new MimeMessage(session);

        // Set the sender's email address
        InternetAddress sender = new InternetAddress(email);
        emailMessage.setFrom(sender);

        // Set the recipient's email address
        InternetAddress recipient = new InternetAddress(to);
        emailMessage.addRecipient(Message.RecipientType.TO, recipient);

        // Set the subject and the message body
        emailMessage.setSubject(subject);
        emailMessage.setText(message);

        // Get the authorized credentials
        Credential credential = credentialsPair.first.first;

        // Create a Gmail service object
        Gmail gmailService = getGmailService(credential);

        // Create a message object and send the email
        Message messageObject = createMessageWithEmail(emailMessage);
        gmailService.users().messages().send("me", messageObject).execute();
    }

    private static Message createMessageWithEmail(MimeMessage emailMessage) throws MessagingException, IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        emailMessage.writeTo(baos);
        String encodedEmail = Base64.encodeBase64URLSafeString(baos.toByteArray());
        return new Message().setRaw(encodedEmail);
    }

    private static Pair<Pair<Credential, String>, Boolean> authorizeGmail() throws IOException {
        // Load client secrets from a resource file
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
                new InputStreamReader(GoogleMail.class.getResourceAsStream("/client_secrets.json")));

        // Define the OAuth 2.0 scopes to request
        Set<String> scopes = new HashSet<>();
        scopes.add(GmailScopes.GMAIL_SEND);

        // Build the Google Authorization Code Flow object
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes)
                .setDataStoreFactory(new FileDataStoreFactory(DATA_STORE_DIRECTORY))
                .build();

        // Request the user's authorization
        return new MyAuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    }
}

// Call the sendEmail method to send the email
GoogleMail.sendEmail("recipient@example.com", "Subject", "Message");
登入後複製

附加說明:

  • authorizeGmail( ) 方法執行oAuth2 驗證並傳回一對憑證和電子郵件地址。
  • 為了請求使用者授權,使用 MyAuthorizationCodeInstalledApp 類,顯示一個簡單的使用者介面。
  • sendEmail() 方法使用 Gmail 服務和 MIME 訊息發送電子郵件。
  • 為了避免對敏感資訊進行硬編碼,請考慮對客戶端機密和其他機密使用環境變數或機密管理器憑證。

以上是我可以在沒有任何配置的情況下使用 Java 透過本機 SMTP 伺服器發送電子郵件嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1655
14
CakePHP 教程
1414
52
Laravel 教程
1307
25
PHP教程
1253
29
C# 教程
1227
24
公司安全軟件導致應用無法運行?如何排查和解決? 公司安全軟件導致應用無法運行?如何排查和解決? Apr 19, 2025 pm 04:51 PM

公司安全軟件導致部分應用無法正常運行的排查與解決方法許多公司為了保障內部網絡安全,會部署安全軟件。 ...

如何將姓名轉換為數字以實現排序並保持群組中的一致性? 如何將姓名轉換為數字以實現排序並保持群組中的一致性? Apr 19, 2025 pm 11:30 PM

將姓名轉換為數字以實現排序的解決方案在許多應用場景中,用戶可能需要在群組中進行排序,尤其是在一個用...

IntelliJ IDEA是如何在不輸出日誌的情況下識別Spring Boot項目的端口號的? IntelliJ IDEA是如何在不輸出日誌的情況下識別Spring Boot項目的端口號的? Apr 19, 2025 pm 11:45 PM

在使用IntelliJIDEAUltimate版本啟動Spring...

如何優雅地獲取實體類變量名構建數據庫查詢條件? 如何優雅地獲取實體類變量名構建數據庫查詢條件? Apr 19, 2025 pm 11:42 PM

在使用MyBatis-Plus或其他ORM框架進行數據庫操作時,經常需要根據實體類的屬性名構造查詢條件。如果每次都手動...

如何使用MapStruct簡化系統對接中的字段映射問題? 如何使用MapStruct簡化系統對接中的字段映射問題? Apr 19, 2025 pm 06:21 PM

系統對接中的字段映射處理在進行系統對接時,常常會遇到一個棘手的問題:如何將A系統的接口字段有效地映�...

Java對像如何安全地轉換為數組? Java對像如何安全地轉換為數組? Apr 19, 2025 pm 11:33 PM

Java對象與數組的轉換:深入探討強制類型轉換的風險與正確方法很多Java初學者會遇到將一個對象轉換成數組的�...

電商平台SKU和SPU數據庫設計:如何兼顧用戶自定義屬性和無屬性商品? 電商平台SKU和SPU數據庫設計:如何兼顧用戶自定義屬性和無屬性商品? Apr 19, 2025 pm 11:27 PM

電商平台SKU和SPU表設計詳解本文將探討電商平台中SKU和SPU的數據庫設計問題,特別是如何處理用戶自定義銷售屬...

如何利用Redis緩存方案高效實現產品排行榜列表的需求? 如何利用Redis緩存方案高效實現產品排行榜列表的需求? Apr 19, 2025 pm 11:36 PM

Redis緩存方案如何實現產品排行榜列表的需求?在開發過程中,我們常常需要處理排行榜的需求,例如展示一個�...

See all articles