Email and working with it in Java applications

Disclaimer

The article is written for beginners and those who want to understand step by step how working with e-mail from Java applications works. Those wishing to quickly understand how to send emails from Spring applications can skip to part 3.



I decided to write this article because I did not find Russian-language sources about working with e-mail from Java, describing the available libraries quite fully. On HabrΓ© there is an article devoted to a very narrow task of reading letters (and displaying their contents to the console) and an article with how-to how to send a

letter with attachments using Spring Email. There are also several articles ( for example ) on thematic resources that lead the procedure for working

with e-mail. What I lacked in those sources was an explanation of the fundamentals of

email and a high-profile look at existing Java mail libraries.



For the same paw-like ones like me, this article was written. It provides an overview of how email works, explains the basic concepts of the Jakarta Mail library, and gives tips on how to work with email in Spring applications.



Content:



  1. Email
  2. Working with email with Jakarta Mail
  3. Working with Email in Spring





1. Email



Today, e-mail seems to be an outdated technology, which is needed only to register on sites where they forgot to attach authorization using Google, Vk or Facebook account. It may be, but you’re probably still getting build drop emails from your CI tool or pull request notifications from your repository to your inbox.



. , , .. -. , , , : ., Gmail .



: Postfix, Sendmail, Apache James, Zimbra.



Outlook The Bat!, - Gmail ..



, . "". SMTP . SMTP. , POP3 IMAP. POP3 . IMAP ,

.



Email transition





:



  • β€” , , .
  • β€” , html, , .


ASCII, , html-, , . , MIME- β€” -.



SMTP. POP3, IMAP.



, β€” .





OSI TCP.

, SSL.



SMTP



Simple Mail Transfer Protocol β€” . .



SMTP 25 587. SMTPS 465.



POP3



Post Office Protocol v3 β€” . . POP3 . , .



POP3 110. POP3S 995.



IMAP



Internet Message Access Protocol β€” . POP3. IMAP - ,

.



IMAP 143. IMAPS 993.



MIME-



Multipurpose Internet Mail Extensions β€” -. MIME , , , SMTP HTTP.



MIME , , HTTP.



, . β€” , β€” .



image/jpeg


MIME .

. multipart, .






2. Jakarta Mail



Jakarta Mail β€” / , , Java-. Jakarta EE. JavaMail, 2017 Jakarta.



Java EE, , . javax.mail. Reference Implementation β€” SMTP, POP3, IMAP. , , com.sun.mail. , Reference Implementation, .



, , Jakarta Mail JavaBeans Activation Framework β€” .



Jakarta Mail 1.6.5, 2.0.0, ""

javax.mail jakarta.mail.



Jakarta Mail . SMTP IMAP POP3 .





, . Jakarta Mail Transport Store .



-, Properties. SMTP- . :



mail.transport.protocol = smtps
mail.smtp.host = smtp.yandex.ru
mail.smtp.port = 465
mail.smtp.user = artem.boiar
mail.smtp.ssl.enable = true
mail.smtp.auth = true
mail.debug = true


.





Properties :



final Session session = Session.getInstance(mailProperties, authenticator);


. . - .





Authenticator, getPasswordAuthentication() ( null, β€” ).



β€” . PasswordAuthentication, DTO .



final Authenticator authenticator = new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(
            this.getDefaultUserName(),
            PropUtils.getPassword()
        );
    }
}


, . Authenticator: IP , ,

.



, - , , :



  • Message β€” ;
  • BodyPart β€” : ;
  • Address β€” ;
  • Folder β€” , ;
  • SearchTerm β€” ;
  • MailEvent β€” , .

    .


β€” .





Message Inheritance



Message, β€” MimeMessage ( ).



Message scheme



: , , , .,- : . BodyPart, Multipart. β€” .



. :



final Message message = new MimeMessage(session);


. , Message RecipientType, :



  • TO β€” ;
  • CC β€” ;
  • BCC β€” .


.



Recipients types



message.setFrom("artem.boiar@yandex.ru");
message.setRecipients(Message.RecipientType.TO, "joshua.bloch@google.com");
message.setRecipients(Message.RecipientType.CC, "tagir.valeev@jetbrains.com");
message.setRecipients(Message.RecipientType.BCC, "sergey.egorov@pivotal.com");
message.setSubject("Java 20 new hot features");




, . Flags:



  • ANSWERED β€”
  • DELETED β€”
  • DRAFT β€”
  • FLAGGED β€”
  • RECENT β€”
  • SEEN β€”
  • USER β€”


setFlag(Flag, boolean set).





.



Address β€” InternetAddress ( NewsAddress , Usenet').



InternetAddress , :



trisha.gee@jetbrains.com


:



internetAddress.setPersonal(" ");


InternetAddress , :



InternetAddress[] recipients = InternetAddress.parse(
    "kuksenko@oracle.com, baruh@jfrog.com, golodnyj@yandex.ru");


β€” , , @Email, Bean Validation.





β€” , . , .



Jakarta Mail BodyPart MimeBodyPart.

disposition:



  • INLINE
  • ATTACHMENT .


, , , .



MIME- :



  • text/plain
  • application/octet-stream .


:



final MimeBodyPart mailBody = new MimeBodyPart();
final MimeBodyPart attachment = new MimeBodyPart();


UML- , , Part, , . . β€” - .





. setText(), β€” attachFile() setContent().



mailBody.setText("Java 20 new features.\nLook at the attachments.");
attachment.attachFile(file);


MIME- .







void saveFile(File)

void writeTo(OutputStream) .





BodyPart Multipart. MimeBodyPart MimeMultipart.



final Multipart multipart = new MimeMultipart();
for (BodyPart bodyPart: bodyParts) {
    //cannot use streams because of checked exception
    multipart.addBodyPart(bodyPart);
}


:



message.setContent(multipart);




. INBOX ( POP3 ).



. - : , β€” (, IMAP) , .



. . , , open(int mode) : READ_ONLY β€” READ_WRITE.



Folder folder = store.getDefaultFolder();
folder.open(Folder.READ_WRITE);


, .



getMessages(), :



Message[] messages = folder.getMessages();


, 1. .



IMAP

. , , fetch() Folder, .



, , DELETED.





Jakarta Mail . SearchTerm, : , , , . .



:



final FromTerm fromTerm = new FromTerm(new InternetAddress("artem.boiar@yandex.ru"));
final SubjectTerm subjectTerm = new SubjectTerm("Java");
final AndTerm termsSummary = new AndTerm(fromTerm, subjectTerm);
final Message[] foundMessages = folder.search(termsSummary);





3. Spring



Jakarta Mail Spring- Spring Email, API Jakarta Mail.

org.springframework.mail, spring-boot-starter-mail.



Java- , ( - ). Spring Email API .



β€” Spring Mail β€” .



Spring Email Scheme



Spring Email , . , send().



: MIME-. , MIME- html-, .





SimpleMailMessage. Jakarta Mail β€” Java.



final SimpleMailMessage simpleMail = new SimpleMailMessage();
simpleMail.setFrom("artem.boiar@yandex.ru");
simpleMail.setTo("yegor.bugaenko@huawei.com");
simpleMail.setSubject("Java 20 new hot features");
simpleMail.setText("Java 20 new hot features. No attachments :(");


MailSender.



this.mailSender.send(simpleMail);


MIME-



MIME- MimeMessage Jakarta Mail. , MIME- MimeMailMessage, SimpleMailMessage MailMessage.



MimeMessage - β€” MimeMessageHelper. ,

. : MIME- :



final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
final MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);

messageHelper.setFrom("artem.boiar@yandex.ru");
messageHelper.setTo("artyom.boyarshinov@cosysoft.ru");
messageHelper.setSubject("Java 20 new hot features");
messageHelper.setText("Java 20 new hot features. Look at the attachment.\nAlso look at my great cat!");
messageHelper.addInline("", FileUtils.getImage());
messageHelper.addAttachment("java-new-features.txt", FileUtils.getFile());


MimeMessageHelper BodyPart, Multipart, API.



MIME- JavaMailSender:



this.javaMailSender.send(mimeMessage);


Spring Email callback- MIME- β€” MimeMessagePreparator. Consumer, MimeMessage.



final MimeMessagePreparator preparator = mimeMessage -> {
    final MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);

    messageHelper.setFrom("artem.boiar@yandex.ru");
    messageHelper.setTo("vlad.mihalcea@hibernate.com");
    messageHelper.setSubject("Java 20 new hot features");
    messageHelper.setText("Java 20 new hot features. Look at the attachment");
    messageHelper.addAttachment("java-new-features.txt", FileUtils.getFile());
};




Jakarta Mail, Spring Email .

runtime Jakarta Mail.



MailSendException. , , getFailedMessages():



catch (MailSendException exc) {
    Map<Object, Exception> exceptionsByMails = exc.getFailedMessages();
    //...
}


Spring Mail



Spring Email SMTP application.properties / application.yml -. , JavaMailSenderImpl .



spring:
  mail:
    protocol: smtps
    host: smtp.yandex.ru
    port: 465
    username: artem.boiar
    password: passw0rd







1



  • . , . . .
  • . .
  • . .


2



  • Jakarta Mail.
  • Github Jakarta Mail.
  • .
  • Eliote Rusty Harold. JavaMail API β€” 2013.


3






All Articles