Java如何通过TLS使用Gmail发送电子邮件?
以下示例显示了如何通过TLS连接使用GmailSMTP发送电子邮件。中username和password是用于验证您对Gmail的。
createConfiguration()方法中定义了用于连接到GmailSMTP的配置/属性。这些属性包括诸如SMTP主机地址,端口号等信息。
要通过SSL使用Gmail发送电子邮件,请参见以下代码片段。如何通过SSL使用Gmail发送电子邮件?
让我们看看下面的代码片段:
package org.nhooo.example.mail; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Date; import java.util.Properties; public class GmailSendEmailTLS { private static final String USERNAME = "nhooo"; private static final String PASSWORD = "********"; public static void main(String[] args) throws Exception { //电子邮件信息,例如从,到,主题和内容。 String mailFrom = "nhooo@gmail.com"; String mailTo = "nhooo@gmail.com"; String mailSubject = "TLS - Gmail Send Email Demo"; String mailText = "TLS - Gmail Send Email Demo"; GmailSendEmailTLS gmail = new GmailSendEmailTLS(); gmail.sendMail(mailFrom, mailTo, mailSubject, mailText); } private void sendMail(String mailFrom, String mailTo, String mailSubject, String mailText) throws Exception { Properties config = createConfiguration(); //创建一个邮件会话。我们需要提供用户名和 //Gmail验证的密码。 Session session = Session.getInstance(config, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( GmailSendEmailTLS.USERNAME, GmailSendEmailTLS.PASSWORD ); } }); //创建电子邮件 Message message = new MimeMessage(session); message.setSentDate(new Date()); message.setFrom(new InternetAddress(mailFrom)); message.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo)); message.setSubject(mailSubject); message.setText(mailText); //发送消息 Transport.send(message, GmailSendEmailTLS.USERNAME, GmailSendEmailTLS.PASSWORD); } private Properties createConfiguration() { return new Properties() {{ put("mail.smtp.auth", "true"); put("mail.smtp.host", "smtp.gmail.com"); put("mail.smtp.port", "587"); put("mail.smtp.starttls.enable", "true"); }}; } }
Maven依赖
<!-- http://repo1.maven.org/maven2/javax/mail/javax.mail-api/1.5.6/javax.mail-api-1.5.6.jar --> <dependency> <groupId>javax.mail</groupId> <artifactId>javax.mail-api</artifactId> <version>1.5.6</version> </dependency> <!-- http://repo1.maven.org/maven2/javax/mail/mail/1.4.7/mail-1.4.7.jar --> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency>