How to Send emails from Google Mail using JavaMail API
With this code you can send emails through your Google Mail account using the JavaMail API.
Firstly, if you don't already have the JavaMail API, visit JavaMail API and download it.
If any of you need help importing the API, please post.
Here is the code. Update the code with your Google Mail account details.
Code Java:
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class SimpleGoogleEmail {
private static final String SMTP_HOST_NAME = "smtp.gmail.com";
private static final int SMTP_HOST_PORT = 465;
private static final String SMTP_AUTH_USER = "username@gmail.com";
private static final String SMTP_AUTH_PWD = "yourPassword";
public static void main(String[] args) throws Exception{
new SimpleGoogleEmail().test();
}
public void test() throws Exception{
Properties props = new Properties();
props.put("mail.transport.protocol", "smtps");
props.put("mail.smtps.host", SMTP_HOST_NAME);
props.put("mail.smtps.auth", "true");
// props.put("mail.smtps.quitwait", "false");
Session mailSession = Session.getDefaultInstance(props);
mailSession.setDebug(true);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
// message subject
message.setSubject("Java Programming Forums");
// message body
message.setContent("Hey! Visit http://www.JavaProgrammingForums.com", "text/plain");
message.addRecipient(Message.RecipientType.TO,
new InternetAddress("from@emailaddress.com"));
transport.connect
(SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
}
}
Re: How to Send emails from Google Mail using JavaMail API
Just showing some love for this post I've always messed around with the mail api, but never could figure out the connect method
Thanks
EDIT:
For people using the newer version of Mail api use:
Code :
MimeBodyPart mbp = new MimeBodyPart();
mbp.setText(body);
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp);
message.setContent(mp);
To set the body/message
Re: How to Send emails from Google Mail using JavaMail API
Quote:
Originally Posted by
Time
For people using the newer version of Mail api use:
Code :
MimeBodyPart mbp = new MimeBodyPart();
mbp.setText(body);
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp);
message.setContent(mp);
To set the body/message
The old way still works. There is no need to use MultiPart if the email is plain text and does not contain attachments or inlines.
Spring 3
Re: How to Send emails from Google Mail using JavaMail API
Thank you all for your answers. I've now figured it out.