Статьи

Почта Java, отправленная через TLS

Аннотация

Цель этого блога — показать, как использовать Java Mail для отправки электронной почты с использованием SMTP-сервера с подключением TLS.

отказ

Этот пост является исключительно информативным. Критически подумайте, прежде чем использовать любую представленную информацию. Учитесь на этом, но в конечном итоге принимайте свои собственные решения на свой страх и риск.

Требования

Я сделал всю работу для этого поста, используя следующие основные технологии. Вы можете сделать то же самое с разными технологиями или версиями, но без гарантий.

  • NetBeans 11.2
  • Maven 3.3.9 (в комплекте с NetBeans)
  • Java 11 (zulu11.35.15-ca-jdk11.0.5-win_x64)
1
2
3
4
5
6
<dependency>
  <groupId>javax.mail</groupId>
  <artifactId>mail</artifactId>
  <version>1.4</version>
  <scope>test</scope>
</dependency>

Скачать

Посетите мою страницу GitHub https://github.com/mjremijan, чтобы увидеть все мои проекты с открытым исходным кодом. Код для этого поста находится по адресу https://github.com/mjremijan/thoth-email в модуле thoth-email-via-tls .

свойства

В этом примере используется файл smtp-tls-outlook.properties для хранения информации о SMTP-сервере. Для тестирования я использовал свою личную учетную запись Outlook, поэтому в названии файла свойств использовалось слово outlook . Важным является содержимое файла, показанное в листинге 1.

Листинг 1 — Файл свойств

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# This is the name of the SMTP host machine.
host=
 
# This is the port number of the SMTP host machine.
# The same host may support both SSL and TLS but on
# different ports. So make sure you get the TLS port.
port=
 
# This is what you use in the “username” field when
# you login. Typically this is the same as your email
# address, but this isn’t always the case.
username=
 
# This is what you use in the “password” field when
# you login. This value is CLEAR TEXT, so keep this
# properties file safe.
password=
 
# This is the email address you want for the
# email’s FROM field. Enter the value using
# the format shown below. Typically this is
# just your email address for the account.
from=FIRSTNAME LASTNAME <ADDRESS@EMAIL.COM>
 
# This is the email address you want for the
# email’s REPLY_TO field. Enter the value using
# the format shown below. Typically this is
# just your email address for the account. Also
# typically this is the same as `from` above.
# But be warned, if an email’s FROM and REPLY_TO
# are different, that’s may be flagged as spam
# and never be delivered. So keep `from` and
# `reply` the same for initial testing
reply=FIRSTNAME LASTNAME <ADDRESS@EMAIL.COM>
 
# This is the email address you want to send
# the email to. For testing, it’s a good idea
# to send it to yourself first.
to=FIRSTNAME LASTNAME <ADDRESS@EMAIL.COM>

Теперь, когда у вас есть файл свойств, давайте посмотрим на код.

Код

Это тест JUnit, демонстрирующий, как использовать Java Mail для отправки электронной почты с использованием SMTP-сервера с подключением TLS. В листинге 2 показан код.

ПРИМЕЧАНИЕ. Для первоначального тестирования всегда проверяйте папку СПАМ. Всегда можно добавить правило для доставки в ваш почтовый ящик.

Листинг 2 — Пример Java Mail

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
package org.thoth.email.via.tls;
 
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
 
public class TlsTest {
 
  public TlsTest() {
  }
 
  protected String now, hostname;
 
  protected Properties outlook;
 
  @BeforeEach
  public void setUp() throws Exception {
    now = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss a").format(new Date());
    hostname = InetAddress.getLocalHost().getHostName();
    outlook = new Properties();
    outlook.load(this.getClass().getResourceAsStream("/smtp-tls-outlook.properties"));
  }
 
  @Test
  public void a_test() throws Exception {
 
    // Create MimeMultipart
    MimeMultipart content = new MimeMultipart("related");
 
    // html part
    {
      MimeBodyPart textPart = new MimeBodyPart();
      textPart.setText("<html><body>"
        + "<p>Time: "+now+"</p>"
        + "<p>From: "+hostname+"</p>"
        + "</body></html>"
        , "UTF8", "html");
      content.addBodyPart(textPart);
    }
 
    // properties
    Properties props = new Properties();
    {
      props.setProperty("mail.smtp.auth", "true");
      props.setProperty("mail.smtp.host", outlook.getProperty("host"));
      props.setProperty("mail.smtp.port", outlook.getProperty("port"));
      props.setProperty("mail.smtp.starttls.enable", "true");
 
    }
 
    Session smtp = null;
    {
      smtp = Session.getInstance(props, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
          return new PasswordAuthentication(
              outlook.getProperty("username")
            , outlook.getProperty("password")
          );
        }
      });
      smtp.setDebug(true);
      smtp.setDebugOut(System.out);
    }
 
 
    MimeMessage m = new MimeMessage(smtp);
    {
      m.setRecipient(Message.RecipientType.TO, new InternetAddress(outlook.getProperty("to")));
      m.setSubject("thoth-email TLS test " + now);
 
      InternetAddress from = null;
      {
        from = new InternetAddress(outlook.getProperty("from"));
        from.setPersonal("Thoth Email");
        m.setFrom(from);
      }
 
      InternetAddress reply = null;
      {
        reply = new InternetAddress(outlook.getProperty("reply"));
        m.setReplyTo(new InternetAddress[] {reply});
      }
 
 
      m.setContent(content);
    }
 
    Transport.send(m);
  }
 
}

Резюме

Код для отправки почты не очень сложный. Успешное получение электронного письма без пометки как СПАМ — это другой вопрос. Но если вы будете следовать этому примеру, использовать действующую учетную запись и не злоупотреблять ею, у вас все будет в порядке. В этом блоге показано, как использовать Java Mail для отправки электронной почты, используя SMTP-сервер с подключением TLS.

Опубликовано на Java Code Geeks с разрешения Майкла Ремиджана, партнера нашей программы JCG. Смотрите оригинальную статью здесь: Java Mail отправлено через TLS

Мнения, высказанные участниками Java Code Geeks, являются их собственными.