使用 Gmail 配置 Java 邮件服务器

使用 Gmail 配置 Java 邮件服务器

如何配置 Java 邮件程序以使用 Gmail 服务器读取和撰写邮件?

答案1

最近在写一个可以发送电子邮件的代码,希望对大家有用。

您也可能需要阅读此内容。设置、设置更改等。

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class EmailClient {

    private static final String SMTP_HOST_NAME = "smtp.gmail.com";
    private static final String SMTP_AUTH_USER = "*EMAIL ADDRESS YOU WANT THE EMAIL TO COME FROM*";
    private static final String SMTP_AUTH_PWD = "*EMAIL ADDRESS PASSWORD*";

    public static void main(String[] args) {

        EmailClient em = new EmailClient();

        // array of email addresses you want this email to go to
        String[] rec = new String[*any number you desire*];

        try {
            em.postMail(rec, "Holy crap!", "This was actually sent from a Java program!", "*Your email address*");
        } catch (Exception e) {
            System.err.println("Our apologies. We were unable to send the email at this time.");
        }

    } // end main

    public void postMail(String recipients[], String subject, String message, String from) throws MessagingException {

        //boolean debug = false;

        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable","true");
        props.put("mail.smtp.port", 587); // as required by Gmail

        Authenticator auth = new SMTPAuthenticator();
        Session session = Session.getDefaultInstance(props, auth);

        //session.setDebug(debug);

        // create a message
        Message msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);

        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setContent(message, "text/plain");
        Transport.send(msg);

    }

    private class SMTPAuthenticator extends javax.mail.Authenticator {

        public PasswordAuthentication getPasswordAuthentication() {
            String username = SMTP_AUTH_USER;
            String password = SMTP_AUTH_PWD;
            return new PasswordAuthentication(username, password);
        }
    }
}

相关内容