検索
ホームページJava&#&チュートリアル設定を行わずに、localhost SMTP サーバーで Java を使用して電子メールを送信できますか?

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

Java を使用した電子メールの送信

問題:

接続により Java を使用して電子メールを送信しようとするとエラーが発生するローカルホストの SMTP に関する問題

質問:

提供されたコードは電子メールの送信に使用できますか?

回答:

Java を使用して電子メールを送信するために提供されているコードは、メール サーバーのデフォルト設定を利用するため、すべての場合に機能するとは限りません。具体的には、localhost 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>

補足:

  • The authorizeGmail( ) メソッドは oAuth2 認証を実行し、Credential と電子メールのペアを返します。アドレス。
  • ユーザー認証を要求するには、MyAuthorizationCodeInstalledApp クラスが使用され、単純なユーザー インターフェイスが表示されます。
  • sendEmail() メソッドは、Gmail サービスと MIME メッセージを使用して電子メールを送信します。
  • 機密情報のハードコーディングを回避するには、クライアント シークレットなどに環境変数またはシークレット マネージャーを使用することを検討してください。資格情報。

以上が設定を行わずに、localhost SMTP サーバーで Java を使用して電子メールを送信できますか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

VSCode Windows 64 ビットのダウンロード

VSCode Windows 64 ビットのダウンロード

Microsoft によって発売された無料で強力な IDE エディター

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

WebStorm Mac版

WebStorm Mac版

便利なJavaScript開発ツール

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン