Sending gmail using java

Как отправить Email в Java?

Давайте разберемся, как отправить email в Java используя почтовый сервер Google Gmail.

Как я уже говорил отправлять мы будем через почтовый сервер Gmail.

Для этого нам нужны данные Outgoing Mail (SMTP) Server:

Host: smtp.gmail.com Use Authentication: Yes Port for TLS/STARTTLS: 587 Port for SSL: 465

И уже с их помощью мы можем обращаться к серверу Gmail.

Немного теории Wiki

TLS (Transport Layer Security) — криптографические протоколы, обеспечивающие защищённую передачу данных между узлами в сети Интернет, TLS и SSL используют асимметричную криптографию для обмена ключами, симметричное шифрование для конфиденциальности и коды аутентичности сообщений для сохранения целостности сообщений.

SSL (Secure Sockets Layer — уровень защищённых сокетов) — криптографический протокол, который обеспечивает безопасность связи. Он использует асимметричную криптографию для аутентификации ключей обмена, симметричное шифрование для сохранения конфиденциальности, коды аутентификации сообщений для целостности сообщений. Протокол широко используются для обмена мгновенными сообщениями и передачи голоса через IP, в таких приложениях, как электронная почта, Интернет-факс и др.

Мы попробуем отправить сообщение оба способами.

Шаг 1

Создаем maven проект и называем его SendMail.

И добавляем в него зависимость библиотеки JavaMail API:

Шаг 2

После создаем в нем пакет com.devcolibri.tls и тут создадим класс Sender.java:

package com.devcolibri.tls; import java.util.Properties; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class Sender < private String username; private String password; private Properties props; public Sender(String username, String password) < this.username = username; this.password = password; props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); >public void send(String subject, String text, String fromEmail, String toEmail) < Session session = Session.getInstance(props, new Authenticator() < protected PasswordAuthentication getPasswordAuthentication() < return new PasswordAuthentication(username, password); >>); try < Message message = new MimeMessage(session); //от кого message.setFrom(new InternetAddress(username)); //кому message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail)); //Заголовок письма message.setSubject(subject); //Содержимое message.setText(text); //Отправляем сообщение Transport.send(message); >catch (MessagingException e) < throw new RuntimeException(e); >> >

В строке 21 мы активируем протокол TLS.

Шаг 3

Теперь попробуем написать отправку по протоколу SSL.

Создаем пакет com.devcolibri.ssl и тут создадим класс Sender.java:

package com.devcolibri.ssl; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; public class Sender < private String username; private String password; private Properties props; public Sender(String username, String password) < this.username = username; this.password = password; props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); >public void send(String subject, String text, String fromEmail, String toEmail) < Session session = Session.getDefaultInstance(props, new Authenticator() < protected PasswordAuthentication getPasswordAuthentication() < return new PasswordAuthentication(username, password); >>); try < Message message = new MimeMessage(session); //от кого message.setFrom(new InternetAddress(username)); //кому message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail)); //тема сообщения message.setSubject(subject); //текст message.setText(text); //отправляем сообщение Transport.send(message); >catch (MessagingException e) < throw new RuntimeException(e); >> >

В строке 21 мы указываем, что будем использовать для отправки протокол SSL.

Шаг 4

Тестируем отправку сообщение оба протоколами:

package com.devcolibri; public class Main < private static com.devcolibri.tls.Sender tlsSender = new com.devcolibri.tls.Sender("", ""); private static com.devcolibri.ssl.Sender sslSender = new com.devcolibri.ssl.Sender("", ""); public static void main(String[] args) < tlsSender.send("This is Subject", "TLS: This is text!", "support@devcolibri.com", "alex@devcolibri.com"); sslSender.send("This is Subject", "SSL: This is text!", "support@devcolibri.com", "alex@devcolibri.com"); >>

В результате вы увидите на посте следующее:

Источник

Java – Send Emails using Gmail SMTP using TLS/SSL

Learn to send emails using the Jakarta Mail API and using the Gmail SMTP Server. We will see the Java examples to send plain text emails as well as emails with attachments.

1. Gmail SMTP Server Details

Google has provided free access to one of its SMTP servers and we can use its Java code to send emails.

  • Gmail SMTP server: smtp.gmail.com
  • Port: 465 (SSL required) / 587 (TLS required)
  • Username: Gmail id
  • Password: The app password

We must create the app password as described in this guide. We cannot use the Gmail password (used to signin in the browser) if we have enabled the 2-factor authentication for the account.

In absense of App password, you will get the “AuthenticationFailedException: 534-5.7.9 Application-specific password required.” error in runtime.

For a typical client application, we need to perform the following steps to send an email:

  • Create a mail message containing the message header and body
  • Create a Session object, which authenticates the user using the Authenticator , and controls access to the message store and transport.
  • Send the message to its recipient list.

Start with adding the following dependencies to the project. Note that the Angus Mail implementation of Jakarta Mail Specification 2.1+ providing a platform-independent and protocol-independent framework to build mail and messaging applications.

 jakarta.mail jakarta.mail-api 2.1.2  org.eclipse.angus jakarta.mail 2.0.1 

The EmailSender is a utility class that accepts the message parameters and sends the email to recipients.

import jakarta.mail.Authenticator; import jakarta.mail.Message; import jakarta.mail.MessagingException; import jakarta.mail.Multipart; import jakarta.mail.PasswordAuthentication; import jakarta.mail.Session; import jakarta.mail.Transport; import jakarta.mail.internet.InternetAddress; import jakarta.mail.internet.MimeBodyPart; import jakarta.mail.internet.MimeMessage; import jakarta.mail.internet.MimeMultipart; import java.util.Date; import java.util.List; import java.util.Properties; public class EmailSender < private static final Properties PROPERTIES = new Properties(); private static final String USERNAME = "admin@gmail.in"; //change it private static final String PASSWORD = "password"; //change it private static final String HOST = "smtp.gmail.com"; static < PROPERTIES.put("mail.smtp.host", "smtp.gmail.com"); PROPERTIES.put("mail.smtp.port", "587"); PROPERTIES.put("mail.smtp.auth", "true"); PROPERTIES.put("mail.smtp.starttls.enable", "true"); >public static void sendPlainTextEmail(String from, String to, String subject, List messages, boolean debug) < Authenticator authenticator = new Authenticator() < protected PasswordAuthentication getPasswordAuthentication() < return new PasswordAuthentication(USERNAME, PASSWORD); >>; Session session = Session.getInstance(PROPERTIES, authenticator); session.setDebug(debug); try < // create a message with headers MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); InternetAddress[] address = ; msg.setRecipients(Message.RecipientType.TO, address); msg.setSubject(subject); msg.setSentDate(new Date()); // create message body Multipart mp = new MimeMultipart(); for (String message : messages) < MimeBodyPart mbp = new MimeBodyPart(); mbp.setText(message, "us-ascii"); mp.addBodyPart(mbp); >msg.setContent(mp); // send the message Transport.send(msg); > catch (MessagingException mex) < mex.printStackTrace(); Exception ex = null; if ((ex = mex.getNextException()) != null) < ex.printStackTrace(); >> > >

To test the above class, we can invoke the sendPlainTextEmail() method as follows:

import java.util.List; public class MailTest < public static void main(String[] args) < EmailSender.sendPlainTextEmail("sender@gmail.com", "reciever@gmail.com", "Test Email", List.of("Hello", "World"), true); >>

Check the email. You should be able to see the email in your Gmail inbox as follows:

If we do not have TLS support on the server, we can use the SSL support provided in the API. To use SSL, follow these steps:

  • Remove the mail.smtp.starttls.enable property
  • Use port number 465
  • Add SSL support in the properties

The modified properties will be:

Now we can run the above program with modified properties, and we will again get the email in our inbox.

6. Adding Email Attachments

If we want to add the attachments to the email body, we can use the MimeBodyPart.attachFile() method to attach a file.

MimeBodyPart attachmentBodyPart = new MimeBodyPart(); attachmentBodyPart.attachFile(new File("path/to/file"));

In this example, we saw the Java programs to send emails using the Gmail SMTP server to multiple recipients. Drop me your questions in the comments.

Источник

Sending Email Using Java GMail and SMTP

Demonstrates how to securely connect to GMail using Java SMTP classes found in Secure iNet Factory.

java gmail

Google allows GMail account users to access their account using any capable email client such as Microsoft Outlook, Apple Mail.app and others. For this to work GMail provides POP and IMAP access to these client applications so that they can access emails stored on GMail servers. In addition to this, GMail provides access to its SMTP server to allow these clients to send emails through it. In order to prevent abuse such as spamming and to provide increased security the GMail SMTP server requires that you connect using SMTP SSL and login using your account credentials prior to sending any mail. The purpose of this article is to demonstrate how to securely connect to the GMail SMTP server and send mail using a bit of Java code which make use of com.jscape.inet.smtpssl.SmtpSsl class found in Secure iNet Factory. The procedures in this article may also apply to other SMTP servers that provide secure SSL/TLS access.
Prerequisites
GMail account Secure
iNet Factory

Using SmtpSsl to Send Email via GMail SMTP Server The SmtpSsl class implements basic functionality of a secure SMTP client using SSL/TLS. It supports both implicit SSL/TLS on port 465 (default) and explicit SSL/TLS using STARTTLS command on port 25. Below is a Java code snippet that shows how to use SmtpSsl to connect to GMail using implicit SSL, authenticate and then send an email.

import com.jscape.inet.smtpssl.SmtpSsl;
import com.jscape.inet.email.EmailMessage;
// create a new SmtpSsl instance connecting securely via port 465 using implicit SSL
smtp = new SmtpSsl("smtp.gmail.com", 465);
// establish secure connection
// login using gmail account details
smtp.login(username, password);
EmailMessage message = new EmailMessage();
message.setSubject("Sending email via Gmail SMTP");
message.setBody("This is the body of the message");

Summary

This article demonstrates how straightforward and easy it is to connect to a secure SMTP server, in this case GMail, and then send an email.

References

Setting Up SFTP Public Key Authentication On The Command Line

SFTP allows you to authenticate clients using public keys, which means they won’t need a password. Learn how to set this up in the command line online. Read Article

Active vs. Passive FTP Simplified: Understanding FTP Ports

If there are problems connecting to your FTP Server, check your transfer mode. Let JSCAPE help you understand the difference in active & passive FTP. Read Article

Active-Active vs. Active-Passive High-Availability Clustering

The most commonly used high-availability clustering configurations are Active-Active and Active-Passive. Learn the difference between the two online! Read Article

Using Windows FTP Scripts To Automate File Transfers

Learn how to automate file transfers using Windows FTP scripts. This post explains what FTP scripts are and how to create simple scripts to transfer files. Read Article

Источник

Читайте также:  Try python несколько раз
Оцените статью