Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I send an SMTP Message from Java? [duplicate]

Tags:

java

smtp

Possible Duplicate:
How do you send email from a Java app using Gmail?

How do I send an SMTP Message from Java?

like image 455
Allain Lalonde Avatar asked Sep 16 '08 15:09

Allain Lalonde


People also ask

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.

How can I get SMTP server response using JavaMail?

SMTPTransport t = (SMTPTransport)session. getTransport("smtps"); t. send(message); String response = t. getLastServerResponse(); boolean s = t.

What is mail SMTP Starttls enable?

smtp. starttls. enable, to "true". When set, if the server supports the STARTTLS command, it will be used after making the connection and before sending any login information.


1 Answers

Here's an example for Gmail smtp:

import java.io.*; import java.net.InetAddress; import java.util.Properties; import java.util.Date;  import javax.mail.*;  import javax.mail.internet.*;  import com.sun.mail.smtp.*;   public class Distribution {      public static void main(String args[]) throws Exception {         Properties props = System.getProperties();         props.put("mail.smtps.host","smtp.gmail.com");         props.put("mail.smtps.auth","true");         Session session = Session.getInstance(props, null);         Message msg = new MimeMessage(session);         msg.setFrom(new InternetAddress("[email protected]"));;         msg.setRecipients(Message.RecipientType.TO,         InternetAddress.parse("[email protected]", false));         msg.setSubject("Heisann "+System.currentTimeMillis());         msg.setText("Med vennlig hilsennTov Are Jacobsen");         msg.setHeader("X-Mailer", "Tov Are's program");         msg.setSentDate(new Date());         SMTPTransport t =             (SMTPTransport)session.getTransport("smtps");         t.connect("smtp.gmail.com", "[email protected]", "<insert password here>");         t.sendMessage(msg, msg.getAllRecipients());         System.out.println("Response: " + t.getLastServerResponse());         t.close();     } } 

Now, do it this way only if you would like to keep your project dependencies to a minimum, otherwise i can warmly recommend using classes from apache

http://commons.apache.org/email/

Regards

Tov Are Jacobsen

like image 121
4 revs, 2 users 97% Avatar answered Sep 22 '22 23:09

4 revs, 2 users 97%