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?
How do you send email from a Java app using GMail?
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.
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.
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With