Как отправить email из программы java

от admin

JavaMail Example — Send Mail in Java using SMTP

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Today we will look into JavaMail Example to send email in java programs. Sending emails is one of the common tasks in real life applications and that’s why Java provides robust JavaMail API that we can use to send emails using SMTP server. JavaMail API supports both TLS and SSL authentication for sending emails.

JavaMail Example

javamail example, send mail in java, java smtp, java send email Today we will learn how to use JavaMail API to send emails using SMTP server with no authentication, TLS and SSL authentication and how to send attachments and attach and use images in the email body. For TLS and SSL authentication, I am using GMail SMTP server because it supports both of them. You can also choose to go for a Java mail server depending on your project needs. JavaMail API is not part of standard JDK, so you will have to download it from it’s official website i.e JavaMail Home Page. Download the latest version of the JavaMail reference implementation and include it in your project build path. The jar file name will be javax.mail.jar. If you are using Maven based project, just add below dependency in your project.

Java Program to send email contains following steps:

  1. Creating javax.mail.Session object
  2. Creating javax.mail.internet.MimeMessage object, we have to set different properties in this object such as recipient email address, Email Subject, Reply-To email, email body, attachments etc.
  3. Using javax.mail.Transport to send the email message.

The logic to create session differs based on the type of SMTP server, for example if SMTP server doesn’t require any authentication we can create the Session object with some simple properties whereas if it requires TLS or SSL authentication, then logic to create will differ. So I will create a utility class with some utility methods to send emails and then I will use this utility method with different SMTP servers.

JavaMail Example Program

Our EmailUtil class that has a single method to send email looks like below, it requires javax.mail.Session and some other required fields as arguments. To keep it simple, some of the arguments are hard coded but you can extend this method to pass them or read it from some config files.

Notice that I am setting some header properties in the MimeMessage, they are used by the email clients to properly render and display the email message. Rest of the program is simple and self understood. Now let’s create our program to send email without authentication.

Send Mail in Java using SMTP without authentication

Notice that I am using Session.getInstance() to get the Session object by passing the Properties object. We need to set the mail.smtp.host property with the SMTP server host. If the SMTP server is not running on default port (25), then you will also need to set mail.smtp.port property. Just run this program with your no-authentication SMTP server and by setting recipient email id as your own email id and you will get the email in no time. The program is simple to understand and works well, but in real life most of the SMTP servers use some sort of authentication such as TLS or SSL authentication. So we will now see how to create Session object for these authentication protocols.

Send Email in Java SMTP with TLS Authentication

Since I am using GMail SMTP server that is accessible to all, you can set the correct variables in above program and run for yourself. Believe me it works!! 🙂

Java SMTP Example with SSL Authentication

The program is almost same as TLS authentication, just some properties are different. As you can see that I am calling some other methods from EmailUtil class to send attachment and image in email but I haven’t defined them yet. Actually I kept them to show later and keep it simple at start of the tutorial.

JavaMail Example — send mail in java with attachment

To send a file as attachment, we need to create an object of javax.mail.internet.MimeBodyPart and javax.mail.internet.MimeMultipart . First add the body part for the text message in the email and then use FileDataSource to attach the file in second part of the multipart body. The method looks like below.

The program might look complex at first look but it’s simple, just create a body part for text message and another body part for attachment and then add them to the multipart. You can extend this method to attach multiple files too.

JavaMail example — send mail in java with image

Since we can create HTML body message, if the image file is located at some server location we can use img element to show them in the message. But sometimes we want to attach the image in the email and then use it in the email body itself. You must have seen so many emails that have image attachments and are also used in the email message. The trick is to attach the image file like any other attachment and then set the Content-ID header for image file and then use the same content id in the email message body with <img src=’cid:image_id’> .

JavaMail API Troubleshooting Tips

java.net.UnknownHostException comes when your system is not able to resolve the IP address for the SMTP server, it might be wrong or not accessible from your network. For example, GMail SMTP server is smtp.gmail.com and if I use smtp.google.com, I will get this exception. If the hostname is correct, try to ping the server through command line to make sure it’s accessible from your system.

If your program is stuck in Transport send() method call, check that SMTP port is correct. If it’s correct then use telnet to verify that it’s accessible from you machine, you will get output like below.

That’s all for JavaMail example to send mail in java using SMTP server with different authentication protocols, attachment and images. I hope it will solve all your needs for sending emails in java programs.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

3 Different Ways to Send Email With Java

Send Email Java

Email sending functionality is a must-have for all large-scale customer-oriented applications to notify users about application events. It's a straightforward, low-cost, and easy-to-use method of communication with your users, especially to send event-driven notifications like account activation, password changes, and user verification. So, it has become a frequent form of asynchronous communication with end-users, ranging from simple notifications with plain text to comprehensive reports with links and many attachments.

Читать:
Как задать диапазон в питоне

For many years, Java has ranked as one of the most popular programming languages. Enterprises consider Java the ideal language to use since it helps you handle the most common issues that arise when designing enterprise applications.

In this article, I will discuss three different ways to send Emails with Java while discussing the pros and cons of each method.

1. Using JavaMail API

JavaMail API is a platform-independent and protocol-independent framework to develop Java client applications for mails and messaging. It is a generic interface to email programs that provides abstract classes containing objects created in the email system.

  • It is well-structured and widely used.
  • Provides multiple options, including reading, composing, and sending emails.
  • Other programs can use the Java Mail API to make sending mail confirmations or other messages easier.
  • Codes may take a little longer to compile.
  • Using the Mail API may consume a significant amount of JAVA heap space.

Demonstration

Step 1 — Installing JavaMail API

First, you need to include two jar files into your CLASSPATH:

After including jar files, you can start sending emails. However, you need an SMTP server to send emails using JavaMail API. You can easily set up an SMTP server using a provider like Pepipost.

Step 2 — Getting the mail session

As the second step, you need to get the session object. The session object contains all the information related to the host like name, user name, password, etc. For that, you can use one of the methods provided by javax.mail.Session class.

Also, you can pass the username and the password to obtain authentication for a network connection.

Step 3 — Composing the email

You can use the javax.mail.internet.MimeMessage subclass to compose the message. First, you need to pass the session object to MimeMessage class. Then you can configure the sender, receiver, subject, and message body.

Step 4 — Sending the email

Finally, you can use the javax.mail.Transport class to send the email.

The complete code example of sending an email using JavaMail APi will look like below:

2. Using Simple Java Mail

Simple Java Mail is a simple mailing library with a straightforward API. As a result, it's one of the most user-friendly (Java) mailing libraries for sending SMTP emails. Simple Java Mail is a wrapper around the JavaMail API library, and it simplifies the email sending process by removing several classes and properties.

  • This library is robust, small, and lightweight (134kB).
  • It complies with all RFCs and looks good in all email clients.
  • It's also the world's only java mailing library that can send through an authenticated SOCKS proxy.
  • Support for HTML, images, and attachments.
  • Can send email to multiple receivers at once.
  • Small community support compared to JavaMail API.

Demonstration

Sending emails using Simple Java Mail is pretty straightforward. First, you need to create an email object using EmailBuilder . Then, you need to create a mailer object using MailerBuilder and pass the email object to the mailer object to send the email.

In addition to the above, Simple Java Mail provides various options to configure email and the mailer. You can find more details about them in Simple Java Mail documentation.

3. Using a Multi-Channel Notification Service

Multi-channel notification services can notify users across multiple channels such as Emails, SMS, Push Notifications. With the modern application requirements, using a multi-channel notification service like Courier can streamline your notification flow by creating all the relevant channels with them a single API.

  • With a single API, you can notify users across different notification channels.
  • Because all channels use the same API, you won’t have to manage a large codebase, which will make it easier to maintain.
  • Without modifying your code, you can add more notification channels in the future.
  • As a result, your notification service can be managed by any non-technical user.
  • Consuming many notification channels can be costly.
  • The maximum number of notifications you can receive per month limits you.

Demonstration

For this demonstration, I will be using Courier since it offers a free plan of 10,000 emails per month and even provides you with the capability of using your Email Service Provider. Additionally, it integrates seamlessly with popular transactional email APIs such as SendGrid and Amazon SES, allowing you to effectively manage your multi-channel notification workflow. Furthermore, Courier provides you with an easy setup process to help you configure your application to send emails using Gmail in minutes!

Step 1 — Creating a Courier account

You can easily create a free Courier account using the following link — https://app.courier.com/signup.

Step 2 — Creating a notification

After creating the account, you need to create a notification. For that, select the Designer tab from the Courier dashboard. You should see the output shown below.

Creating a Notification

Step 3 — Configuring the providers

Now, click the Configure providers button to integrate your Gmail account.

Configuring Notification Providers

It will ask you to authorize your Google account to send emails and you can find the finalized configuration in the Integrations tab.

Step 5 — Customizing the email template

After adding the provider, you can customize your template by adding a logo, code blocks, bullet lists, and attaching dynamic data.

Customizing Email Template

Step 6 — Authorising Google to send emails

Next, we can install the Courier API to the Java application. First, you need to update the Maven pom.xml file with the below dependency and run mvn compile to download it.

After successfully installing, use the code shown below to send an email through Gmail using Courier.

The Courier email notification has four main properties:

  • to : Provides information used by Courier to identify the recipient of the notification.
  • content : This property is used to add your notification’s title and body.
  • data : Includes the data you want to pass to a message template.
  • routing : Used to customize which channel(s) Courier will potentially deliver the message.

Conclusion

This article discussed three different ways of sending an email using Java. Each of the discussed libraries and services has unique features, and you can choose one based on your requirements.

I hope this article helps you choose the best way to send emails in Java applications. Thank you for reading.

Похожие статьи