使用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 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 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");</string></pair></pair>
附加說明:
- authorizeGmail( ) 方法執行oAuth2 驗證並傳回一對憑證和電子郵件地址。
- 為了請求使用者授權,使用 MyAuthorizationCodeInstalledApp 類,顯示一個簡單的使用者介面。
- sendEmail() 方法使用 Gmail 服務和 MIME 訊息發送電子郵件。
- 為了避免對敏感資訊進行硬編碼,請考慮對客戶端機密和其他機密使用環境變數或機密管理器憑證。
以上是我可以在沒有任何配置的情況下使用 Java 透過本機 SMTP 伺服器發送電子郵件嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本文討論了使用Maven和Gradle進行Java項目管理,構建自動化和依賴性解決方案,以比較其方法和優化策略。

本文使用Maven和Gradle之類的工具討論了具有適當的版本控制和依賴關係管理的自定義Java庫(JAR文件)的創建和使用。

本文討論了使用咖啡因和Guava緩存在Java中實施多層緩存以提高應用程序性能。它涵蓋設置,集成和績效優勢,以及配置和驅逐政策管理最佳PRA

本文討論了使用JPA進行對象相關映射,並具有高級功能,例如緩存和懶惰加載。它涵蓋了設置,實體映射和優化性能的最佳實踐,同時突出潛在的陷阱。[159個字符]

Java的類上載涉及使用帶有引導,擴展程序和應用程序類負載器的分層系統加載,鏈接和初始化類。父代授權模型確保首先加載核心類別,從而影響自定義類LOA


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

禪工作室 13.0.1
強大的PHP整合開發環境

WebStorm Mac版
好用的JavaScript開發工具

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