使用 Java 发送电子邮件
问题:
由于连接原因,尝试使用 Java 发送电子邮件时发生错误本地 SMTP 服务器出现问题。
问题:
提供的代码可以用来发送电子邮件吗?
答案:
所提供的使用 Java 发送电子邮件的代码(使用邮件服务器的默认设置)可能无法在所有情况下工作。具体来说,本地主机 SMTP 服务器默认情况下不太可能正常工作。
解决方案:
要使用 Java 可靠地发送电子邮件,请考虑使用第三方 SMTP 服务器,例如如谷歌邮件。下面的代码片段演示了如何使用 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)