Rumah > Java > javaTutorial > Bolehkah saya menghantar e-mel menggunakan Java dengan pelayan SMTP localhost tanpa sebarang konfigurasi?

Bolehkah saya menghantar e-mel menggunakan Java dengan pelayan SMTP localhost tanpa sebarang konfigurasi?

DDD
Lepaskan: 2024-11-11 08:17:02
asal
731 orang telah melayarinya

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

Menghantar E-mel Menggunakan Java

Isu:

Ralat berlaku apabila cuba menghantar e-mel menggunakan Java disebabkan sambungan masalah dengan localhost SMTP pelayan.

Soalan:

Bolehkah kod yang disediakan digunakan untuk menghantar e-mel?

Jawapan:

Kod yang disediakan untuk menghantar e-mel menggunakan Java, yang menggunakan tetapan lalai untuk pelayan mel, mungkin tidak berfungsi dalam semua kes. Khususnya, pelayan SMTP localhost tidak mungkin berfungsi secara lalai.

Penyelesaian:

Untuk menghantar e-mel dengan pasti menggunakan Java, pertimbangkan untuk menggunakan pelayan SMTP pihak ketiga seperti sebagai Google Mail. Berikut ialah coretan kod yang menunjukkan cara menghantar e-mel melalui pelayan SMTP Google menggunakan API dan pengesahan oAuth2 mereka:

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");
Salin selepas log masuk

Nota Tambahan:

  • The authorizeGmail( ) kaedah melaksanakan pengesahan oAuth2 dan mengembalikan sepasang Kredensial dan an alamat e-mel.
  • Untuk meminta kebenaran pengguna, kelas MyAuthorizationCodeInstalledApp digunakan, memaparkan antara muka pengguna yang mudah.
  • Kaedah sendEmail() menghantar e-mel menggunakan perkhidmatan Gmail dan mesej MIME.
  • Untuk mengelakkan pengekodan keras maklumat sensitif, pertimbangkan untuk menggunakan pembolehubah persekitaran atau pengurus rahsia untuk rahsia pelanggan dan lain-lain kelayakan.

Atas ialah kandungan terperinci Bolehkah saya menghantar e-mel menggunakan Java dengan pelayan SMTP localhost tanpa sebarang konfigurasi?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan