Explain Codes LogoExplain Codes Logo

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

java
email
java-mail
smtp
Alex KataevbyAlex Kataev·Feb 11, 2025
TLDR

You can swiftly compose and dispatch emails from your Java application using the JavaMail API and SMTP:

import javax.mail.*; import javax.mail.internet.*; import java.util.Properties; // Guess what these are? Right, SMTP settings! String host = "smtp.gmail.com"; String port = "587"; String username = "[email protected]"; // Don't forget to replace with your actual email String password = "your-password"; // And here we go with the password! Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); // We love safety, don't we? props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); // Everybody hates spam, but we do need to authenticate to send emails. Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); // Login time! } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(username)); // You are not writing to Santa, put real recipient's email here. message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]")); message.setSubject("Subject Line"); message.setText("Email body"); // The moment of truth! Time to send! Transport.send(message); // And... Voila! Email sent to the stratosphere! System.out.println("Go check your email, folks! I have shot one into the Cloud!"); } catch (MessagingException e) { // Oops... Houston, we have a problem! throw new RuntimeException(e); }

Quick Recap:

  • Use JavaMail classes in conjunction with SMTP server settings for GMail, Yahoo, or Hotmail.
  • Make sure properties include SMTP auth and starttls setups.
  • Use your actual credentials and replace [email protected] with the recipient's email address.
  • We use PasswordAuthentication to gain SMTP server's trust.
  • The Transport.send(message) flings your email into the internet.

Hacker alert: Resist the temptation to hardcode passwords; use environment variables or some other secure method to store sensitive details.

Making it bulletproof

Playing with Exceptions

Instead of catching MessagingException in general, let's get more specific with the types of exceptions we can expect:

// More exceptions than in law school textbooks! } catch (AuthenticationFailedException e) { // Oops! Double-check your password. Or did CAPS LOCK stroll in? } catch (SendFailedException e) { // Address failed. Did we accidentally attempt Owl mail? } catch (MessagingException e) { // Hmm, some general issue. Is the internet on vacation? }

Fine-grained Exception handling will turn your app from a sandbox project into a robust system.

Mind the Send rate and Anti-spam policies

Email providers like GMail are pretty protective and put limits and policies on the volume and style of emails sent; you don't want to be mistaken for a spammer, right?

  • Be gentle, don't bombard with emails.
  • Implement user rate-limiting if necessary.
  • Read the provider's policies. For example, use Gmail guidelines to avoid being flagged as a spammer.

It's not just you: Handling multiple recipients

Sending emails to multiple recipients is like throwing a party:

// Party invites to... InternetAddress[] addresses = { new InternetAddress("[email protected]"), new InternetAddress("[email protected]") //... and don't forget the QA guy }; message.setRecipients(Message.RecipientType.TO, addresses);

Content that shines: Adding HTML/Rich Text

With HTML or Rich text, makes your emails come alive. But, remember, with great power comes great responsibility - don't abuse it.

// Add HTML. Now, go color the world! MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent("<h1>This is Magic!</h1><p>Web development inside an email. Just Java things!</p>", "text/html"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); message.setContent(multipart);

Got Safety? Secure email with TLS

mail.smtp.starttls.enable must be set to true so that TLS secures email communication. Remember: We love safety.

Fortunate short-cuts

Simplifying life with Simple Java Mail

Simple Java Mail library, as the name suggests, simplifies the steps significantly. Here's how to generate an email:

// Simplicity Rocks! Email email = new EmailBuilder() .from("Oliver Queen", "[email protected]") .to("Felicity Smoak", "[email protected]") .subject("Found a new lead") .text("Let's discuss at the base.") .build(); new MailerBuilder() .withSMTPServer("smtp.gmail.com", 587, "[email protected]", "P@ssw0rd") // Arrow can't miss, can it? .buildMailer() .sendMail(email); // Fire away!

A very clean and intuitive approach, right?

Credit where it's due!

If you're using or extending code from any forums or developers, it's only right to give them their due credit. Remember, we are a community.

Don't forget the Logs!

Always catch any possible exceptions when Transport.send() is invoked and note down what happened:

// Here be logs... try { Transport.send(message); System.out.println("Message sent. Check your inbox."); // Postman Pat reporting! } catch (MessagingException e) { System.err.println("Oops. Message not sent."); // Alright, time to investigate. }

And finally, just like we don't leave the water tap running, let's not leave the Transport connection open and waste resources:

// Let's be responsible citizens, shall we? finally { if (transport != null) { try { transport.close(); } catch (MessagingException logOrIgnore) {} System.out.println("Clean and green. Closed the Transport connection."); // Eco-friendly programming, eh? } }