suchen
HeimJavajavaLernprogrammKann ich E-Mails mit Java mit einem Localhost-SMTP-Server ohne Konfiguration senden?

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

E-Mails mit Java senden

Problem:

Beim Versuch, eine E-Mail mit Java zu senden, tritt aufgrund der Verbindung ein Fehler auf Probleme mit dem Localhost-SMTP Server.

Frage:

Kann der bereitgestellte Code zum Versenden von E-Mails verwendet werden?

Antwort:

Der bereitgestellte Code zum Versenden von E-Mails mit Java, der Standardeinstellungen für den Mailserver verwendet, funktioniert möglicherweise nicht in allen Fällen. Insbesondere ist es unwahrscheinlich, dass der SMTP-Server localhost standardmäßig funktionsfähig ist.

Lösung:

Um E-Mails zuverlässig mit Java zu senden, sollten Sie die Verwendung eines SMTP-Servers eines Drittanbieters in Betracht ziehen, z als Google Mail. Hier ist ein Codeausschnitt, der zeigt, wie E-Mails über den SMTP-Server von Google mithilfe der API und der oAuth2-Authentifizierung gesendet werden:

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>

Zusätzliche Hinweise:

  • AuthorizeGmail( )-Methode führt eine oAuth2-Authentifizierung durch und gibt ein Paar aus Anmeldeinformationen und einer E-Mail zurück Adresse.
  • Um die Benutzerautorisierung anzufordern, wird die Klasse MyAuthorizationCodeInstalledApp verwendet, die eine einfache Benutzeroberfläche anzeigt.
  • Die Methode sendEmail() sendet eine E-Mail über den Gmail-Dienst und eine MIME-Nachricht.
  • Um die Festcodierung vertraulicher Informationen zu vermeiden, sollten Sie die Verwendung von Umgebungsvariablen oder eines Secrets-Managers für die Client-Geheimnisse und andere in Betracht ziehen Anmeldeinformationen.

Das obige ist der detaillierte Inhalt vonKann ich E-Mails mit Java mit einem Localhost-SMTP-Server ohne Konfiguration senden?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn

Heiße KI -Werkzeuge

Undresser.AI Undress

Undresser.AI Undress

KI-gestützte App zum Erstellen realistischer Aktfotos

AI Clothes Remover

AI Clothes Remover

Online-KI-Tool zum Entfernen von Kleidung aus Fotos.

Undress AI Tool

Undress AI Tool

Ausziehbilder kostenlos

Clothoff.io

Clothoff.io

KI-Kleiderentferner

AI Hentai Generator

AI Hentai Generator

Erstellen Sie kostenlos Ai Hentai.

Heißer Artikel

R.E.P.O. Energiekristalle erklärten und was sie tun (gelber Kristall)
1 Monate vorBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Beste grafische Einstellungen
1 Monate vorBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Crossplay haben?
1 Monate vorBy尊渡假赌尊渡假赌尊渡假赌

Heiße Werkzeuge

VSCode Windows 64-Bit-Download

VSCode Windows 64-Bit-Download

Ein kostenloser und leistungsstarker IDE-Editor von Microsoft

Notepad++7.3.1

Notepad++7.3.1

Einfach zu bedienender und kostenloser Code-Editor

MinGW – Minimalistisches GNU für Windows

MinGW – Minimalistisches GNU für Windows

Dieses Projekt wird derzeit auf osdn.net/projects/mingw migriert. Sie können uns dort weiterhin folgen. MinGW: Eine native Windows-Portierung der GNU Compiler Collection (GCC), frei verteilbare Importbibliotheken und Header-Dateien zum Erstellen nativer Windows-Anwendungen, einschließlich Erweiterungen der MSVC-Laufzeit zur Unterstützung der C99-Funktionalität. Die gesamte MinGW-Software kann auf 64-Bit-Windows-Plattformen ausgeführt werden.

WebStorm-Mac-Version

WebStorm-Mac-Version

Nützliche JavaScript-Entwicklungstools

SublimeText3 Linux neue Version

SublimeText3 Linux neue Version

SublimeText3 Linux neueste Version