| sitelink1 | http://www.nikhilnishchal.com/tech-blogs...p-of-gmail |
|---|---|
| sitelink2 | |
| sitelink3 | |
| sitelink4 | |
| sitelink5 | |
| sitelink6 |
Most of the case we required to send mail.
We can use gmail smtp to send the mail.
Code to send the mail are following.
Please update mailId and password:
package com.sendmail;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
*
* @author nikhil.nishchal
*
*/
public class SendMailByGMAIL {
//Properties for the SMTP configuration
private static final String MAIL_SMTP_HOST = "smtp.gmail.com";
private static final String MAIL_SMTP_PORT = "465";
private static final String SOCKET_FACTORY = "javax.net.ssl.SSLSocketFactory";
private static final String SMTP_AUTH = "true";
private static final String SMTP_SOCKET_PORT = "465";
private static final String SMTP_USER = "xxxxxx@gmail.com";
private static final String SMTP_PASSWORD = "passwordText";
private static final String MAIL_FROM_EMAIL_ID = "frommail@gmail.com";
private static final String MAIL_TO_EMAIL_ID = "tomail@gmail.com";
public static void main(String[] args) {
//Initialization of properties
Properties props = new Properties();
props.put("mail.smtp.host", MAIL_SMTP_HOST);
props.put("mail.smtp.socketFactory.port", SMTP_SOCKET_PORT);
props.put("mail.smtp.socketFactory.class", SOCKET_FACTORY);
props.put("mail.smtp.auth", SMTP_AUTH);
props.put("mail.smtp.port", MAIL_SMTP_PORT);
//Making authentication session
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(SMTP_USER,
SMTP_PASSWORD);
}
});
try {
System.out.println("Sending mail...");
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(MAIL_FROM_EMAIL_ID));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(MAIL_TO_EMAIL_ID));
message.setSubject("Test Mail Subject");
message.setText("Dear Friend,"
+ "\n\n This is spam free mail, enjoy the text."
+ "\n\n\n\n Thanks");
System.out.println("Mail has been sent...");
} catch (MessagingException e) {
System.out.println("Exception:\n"+e.getMessage());
}
}
}
For this, you need Java mail API.
Java mail API we can download from http://www.oracle.com/technetwork/java/javamail/index-138643.html
