- Java — Sending Email
- Send a Simple E-mail
- Example
- Output
- Send an HTML E-mail
- Example
- This is actual message
- Output
- Send Attachment in E-mail
- Example
- Output
- User Authentication Part
- Sending Emails with Java
- 1. Overview
- 2. Project Setup and Dependency
- 3. Sending a Plain Text and an HTML Email
- 4. Sending Email With an Attachment
- 5. Formatting Email Text
- 6. Conclusion
Java — Sending Email
To send an e-mail using your Java Application is simple enough but to start with you should have JavaMail API and Java Activation Framework (JAF) installed on your machine.
- You can download latest version of JavaMail (Version 1.2) from Java’s standard website.
- You can download latest version of JAF (Version 1.1.1) from Java’s standard website.
Download and unzip these files, in the newly created top level directories you will find a number of jar files for both the applications. You need to add mail.jar and activation.jar files in your CLASSPATH.
Send a Simple E-mail
Here is an example to send a simple e-mail from your machine. It is assumed that your localhost is connected to the Internet and capable enough to send an e-mail.
Example
// File Name SendEmail.java import java.util.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public class SendEmail < public static void main(String [] args) < // Recipient's email ID needs to be mentioned. String to = "abcd@gmail.com"; // Sender's email ID needs to be mentioned String from = "web@gmail.com"; // Assuming you are sending email from localhost String host = "localhost"; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); // Get the default Session object. Session session = Session.getDefaultInstance(properties); try < // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject("This is the Subject Line!"); // Now set the actual message message.setText("This is actual message"); // Send message Transport.send(message); System.out.println("Sent message successfully. "); >catch (MessagingException mex) < mex.printStackTrace(); >> >
Compile and run this program to send a simple e-mail −
Output
$ java SendEmail Sent message successfully.
If you want to send an e-mail to multiple recipients then the following methods would be used to specify multiple e-mail IDs −
void addRecipients(Message.RecipientType type, Address[] addresses) throws MessagingException
Here is the description of the parameters −
- type − This would be set to TO, CC or BCC. Here CC represents Carbon Copy and BCC represents Black Carbon Copy. Example: Message.RecipientType.TO
- addresses − This is an array of e-mail ID. You would need to use InternetAddress() method while specifying email IDs.
Send an HTML E-mail
Here is an example to send an HTML e-mail from your machine. Here it is assumed that your localhost is connected to the Internet and capable enough to send an e-mail.
This example is very similar to the previous one, except here we are using setContent() method to set content whose second argument is «text/html» to specify that the HTML content is included in the message.
Using this example, you can send as big as HTML content you like.
Example
// File Name SendHTMLEmail.java import java.util.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public class SendHTMLEmail < public static void main(String [] args) < // Recipient's email ID needs to be mentioned. String to = "abcd@gmail.com"; // Sender's email ID needs to be mentioned String from = "web@gmail.com"; // Assuming you are sending email from localhost String host = "localhost"; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); // Get the default Session object. Session session = Session.getDefaultInstance(properties); try < // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject("This is the Subject Line!"); // Send the actual HTML message, as big as you like message.setContent("This is actual message
", "text/html"); // Send message Transport.send(message); System.out.println("Sent message successfully. "); > catch (MessagingException mex) < mex.printStackTrace(); >> >
Compile and run this program to send an HTML e-mail −
Output
$ java SendHTMLEmail Sent message successfully.
Send Attachment in E-mail
Here is an example to send an e-mail with attachment from your machine. Here it is assumed that your localhost is connected to the internet and capable enough to send an e-mail.
Example
// File Name SendFileEmail.java import java.util.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public class SendFileEmail < public static void main(String [] args) < // Recipient's email ID needs to be mentioned. String to = "abcd@gmail.com"; // Sender's email ID needs to be mentioned String from = "web@gmail.com"; // Assuming you are sending email from localhost String host = "localhost"; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); // Get the default Session object. Session session = Session.getDefaultInstance(properties); try < // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO,new InternetAddress(to)); // Set Subject: header field message.setSubject("This is the Subject Line!"); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message messageBodyPart.setText("This is message body"); // Create a multipar message Multipart multipart = new MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); // Part two is attachment messageBodyPart = new MimeBodyPart(); String filename = "file.txt"; DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); // Send the complete message parts message.setContent(multipart ); // Send message Transport.send(message); System.out.println("Sent message successfully. "); >catch (MessagingException mex) < mex.printStackTrace(); >> >
Compile and run this program to send an HTML e-mail −
Output
$ java SendFileEmail Sent message successfully.
User Authentication Part
If it is required to provide user ID and Password to the e-mail server for authentication purpose, then you can set these properties as follows −
props.setProperty("mail.user", "myuser"); props.setProperty("mail.password", "mypwd");
Rest of the e-mail sending mechanism would remain as explained above.
Sending Emails with Java
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We’re looking for a new Java technical editor to help review new articles for the site.
1. Overview
In this quick tutorial, we’re going to look at sending an email with and without attachments using the core Java mail library.
2. Project Setup and Dependency
For this article, we’ll be using a simple Maven-based project with a dependency on Angus Mail. This is the Eclipse implementation of the Jakarta Mail API specification:
org.eclipse.angus angus-mail 2.0.1
The latest version can be found here.
3. Sending a Plain Text and an HTML Email
First, we need to configure the library with our email service provider’s credentials. Then we’ll create a Session that’ll be used in constructing our message for sending.
The configuration is via a Java Properties object:
Properties prop = new Properties(); prop.put("mail.smtp.auth", true); prop.put("mail.smtp.starttls.enable", "true"); prop.put("mail.smtp.host", "smtp.mailtrap.io"); prop.put("mail.smtp.port", "25"); prop.put("mail.smtp.ssl.trust", "smtp.mailtrap.io");
In the properties configuration above, we configured the email host as Mailtrap and used the port provided by the service as well.
Now let’s create a session with our username and password:
Session session = Session.getInstance(prop, new Authenticator() < @Override protected PasswordAuthentication getPasswordAuthentication() < return new PasswordAuthentication(username, password); >>);
The username and password are given by the mail service provider alongside the host and port parameters.
Now that we have a mail Session object, let’s create a MimeMessage for sending:
Message message = new MimeMessage(session); message.setFrom(new InternetAddress("[email protected]")); message.setRecipients( Message.RecipientType.TO, InternetAddress.parse("[email protected]")); message.setSubject("Mail Subject"); String msg = "This is my first email using JavaMailer"; MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(msg, "text/html; charset=utf-8"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); message.setContent(multipart); Transport.send(message);
In the snippet above, we first created a message instance with the necessary properties — to, from and subject. This is followed by a mimeBodyPart that has an encoding of text/html since our message is styled in HTML.
Next, we created an instance of MimeMultipart object that we can use to wrap the mimeBodyPart we created.
Finally, we set the multipart object as the content of our message and used the send() of Transport object to do the mail sending.
So, we can say that the mimeBodyPart is contained in the multipart that is contained in the message. This way, a multipart can contain more than one mimeBodyPart.
This is going to be the focus of the next section.
4. Sending Email With an Attachment
Next, to send an attachment, we only need to create another MimeBodyPart and attach the file(s) to it:
MimeBodyPart attachmentBodyPart = new MimeBodyPart(); attachmentBodyPart.attachFile(new File("path/to/file"));
We can then add the new body part to the MimeMultipart object we created earlier:
multipart.addBodyPart(attachmentBodyPart);
That’s all we need to do.
Once again, we set the multipart instance as the content of the message object, and finally we’ll use the send() to do the mail sending.
5. Formatting Email Text
To format and style our email text, we can use HTML and CSS tags.
For example, if we want our text to be bold, we will implement the tag. For coloring the text, we can use the style tag. We can also combine HTML tags with CSS tags if we want to have additional properties, such as bold.
Let’s create a String containing bold-red text:
String msgStyled = "This is my bold-red email using JavaMailer";
This String will hold our styled text to be sent in the email body.
6. Conclusion
In this article, we’ve seen how to use the Jakarta Mail API to send emails even with attachments.
As always, the complete source code is available over on GitHub.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes: