Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I send an e-mail in Java?

I need to send e-mails from a servlet running within Tomcat. I'll always send to the same recipient with the same subject, but with different contents.

What's a simple, easy way to send an e-mail in Java?

Related:

How do you send email from a Java app using GMail?

like image 950
Steve McLeod Avatar asked May 19 '09 20:05

Steve McLeod


People also ask

What is SMTP in java?

SMTP is an acronym for Simple Mail Transfer Protocol. It is an Internet standard for electronic mail (e-mail) transmission across Internet Protocol (IP) networks.

How does mail work in java?

The JavaMail is an API that is used to compose, write and read electronic messages (emails). The JavaMail API provides protocol-independent and plateform-independent framework for sending and receiving mails.

How do I send an email to multiple addresses in java?

Sending Email to Multiple RecipientsFor adding Email in 'TO' field, you may use Message.RecipientType.To . Similarly for adding Email in 'CC' and 'BCC' fields, you will have to use Message.RecipientType.CC and Message. RecipientType. BCC.

Can you send java files over email?

For sending email with attachment, JavaMail API provides some useful classes like BodyPart, MimeBodyPart etc. For better understanding of this example, learn the steps of sending email using JavaMail API first. For sending the email using JavaMail API, you need to load the two jar files: mail.


1 Answers

Here's my code for doing that:

import javax.mail.*; import javax.mail.internet.*;  // Set up the SMTP server. java.util.Properties props = new java.util.Properties(); props.put("mail.smtp.host", "smtp.myisp.com"); Session session = Session.getDefaultInstance(props, null);  // Construct the message String to = "[email protected]"; String from = "[email protected]"; String subject = "Hello"; Message msg = new MimeMessage(session); try {     msg.setFrom(new InternetAddress(from));     msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));     msg.setSubject(subject);     msg.setText("Hi,\n\nHow are you?");      // Send the message.     Transport.send(msg); } catch (MessagingException e) {     // Error. } 

You can get the JavaMail libraries from Sun here: http://java.sun.com/products/javamail/

like image 74
RichieHindle Avatar answered Oct 04 '22 15:10

RichieHindle