Надсилання повідомлень за допомогою SMTP Service Client у Java

SmtpClient з com.aspose.email.services.inetmail.client пакет надсилає повідомлення через SMTP-сервер. Потрібна бібліотека поштового протоколу в classpath. Детальніше — дивіться Налаштування бібліотек поштових протоколів.

Надсилання текстового повідомлення

Створіть повідомлення за допомогою InetMessage.builder(), а потім передайте його до send. Встановіть відправника і хоча б одного одержувача. Для повідомлення без одержувачів, send викидає MailClientException перед тим, як підключитися до сервера. Повідомлення без відправника доходить до одержувачів без From адреса, і клієнт пише попередження в журнал.

import com.aspose.email.services.inetmail.auth.PasswordCredentials;
import com.aspose.email.services.inetmail.client.SmtpClient;
import com.aspose.email.services.inetmail.model.InetMessage;

try (SmtpClient smtp = SmtpClient.builder()
        .host("smtp.example.com")
        .port(587)
        .starttls()
        .credentials(new PasswordCredentials("user@example.com", "password"))
        .build()) {
    InetMessage message = InetMessage.builder()
            .from("user@example.com")
            .to("user@example.com")
            .subject("Weekly report")
            .textBody("The report is ready.")
            .build();
    smtp.send(message);
}

Кожний виклик send відкриває власне з’єднання до сервера і закриває його після надсилання повідомлення.

Підключення без автентифікації

Деякі сервери, наприклад ретранслятори у локальній мережі, приймають повідомлення без автентифікації. Щоб підключитися до такого сервера, не викликайте credentials:

import com.aspose.email.services.inetmail.client.SmtpClient;
import com.aspose.email.services.inetmail.model.InetMessage;

try (SmtpClient smtp = SmtpClient.builder()
        .host("relay.example.com")
        .port(25)
        .noSecurity()
        .build()) {
    smtp.send(InetMessage.builder()
            .from("user@example.com")
            .to("user@example.com")
            .subject("Weekly report")
            .textBody("The report is ready.")
            .build());
}

Встановлення локального імені хоста

Коли клієнт підключається, він надсилає назву локального комп’ютера на сервер. Щоб отримати цю назву, поштовий бібліотека виконує DNS‑lookup локальної адреси. Якщо у комп’ютера немає зворотнього DNS‑запису, пошук може зайняти кілька секунд і повторюється при кожному виклику send. Щоб пропустити пошук, встановіть ім’я за допомогою localHost:

import com.aspose.email.services.inetmail.auth.PasswordCredentials;
import com.aspose.email.services.inetmail.client.SmtpClient;

SmtpClient smtp = SmtpClient.builder()
        .host("smtp.example.com")
        .credentials(new PasswordCredentials("user@example.com", "password"))
        .localHost("client.example.com")
        .build();

Встановлення одержувачів та імені відправника

The to, cc і bcc методи приймають одну або кілька адрес. Щоб показати ім’я відправника, передайте спочатку ім’я, а потім адресу:

import com.aspose.email.services.inetmail.model.InetMessage;

InetMessage message = InetMessage.builder()
        .from("Reports Team", "user@example.com")
        .to("user@example.com", "user2@example.com")
        .cc("user3@example.com")
        .bcc("user4@example.com")
        .subject("Weekly report")
        .textBody("The report is ready.")
        .build();
smtp.send(message);

Надсилання HTML‑повідомлення

Використати htmlBody щоб встановити HTML‑версію повідомлення. Якщо також встановити textBody, повідомлення містить обидві версії, і поштовий клієнт одержувача відображає ту, яку підтримує:

import com.aspose.email.services.inetmail.model.InetMessage;

InetMessage message = InetMessage.builder()
        .from("user@example.com")
        .to("user@example.com")
        .subject("Weekly report")
        .textBody("The report is ready.")
        .htmlBody("<p>The report is <b>ready</b>.</p>")
        .build();
smtp.send(message);

Додавання вкладень

Щоб додати вкладення, створіть InetAttachment об’єкт із назвою файлу, типом вмісту та даними, і передайте його до attach:

import com.aspose.email.services.inetmail.model.InetAttachment;
import com.aspose.email.services.inetmail.model.InetMessage;
import java.nio.charset.StandardCharsets;

byte[] data = "Total: 42".getBytes(StandardCharsets.UTF_8);

InetMessage message = InetMessage.builder()
        .from("user@example.com")
        .to("user@example.com")
        .subject("Weekly report")
        .textBody("The report is attached.")
        .attach(InetAttachment.of("report.txt", "text/plain", data))
        .build();
smtp.send(message);

Обробка помилок

Коли повідомлення не може бути надіслане, наприклад, через відхилення сервером облікових даних, send викидає MailClientException, який розширює java.io.IOException:

import com.aspose.email.services.inetmail.MailClientException;
import com.aspose.email.services.inetmail.model.InetMessage;

try {
    smtp.send(InetMessage.builder()
            .from("user@example.com")
            .to("not a valid address")
            .subject("Weekly report")
            .textBody("The report is ready.")
            .build());
} catch (MailClientException e) {
    System.out.println(e.getMessage() + ": " + e.getCause().getMessage());
}