Skip to content

Instantly share code, notes, and snippets.

@erjan
Last active December 12, 2017 07:09
Show Gist options
  • Save erjan/081afdf4abccd76696d94eb88147095f to your computer and use it in GitHub Desktop.
Save erjan/081afdf4abccd76696d94eb88147095f to your computer and use it in GitHub Desktop.
how to send email with java[working code]
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMailTLS {
public static void main(String[] args) {
final String username = "[email protected]"; // enter your mail id
final String password = "123456";// enter ur password
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]")); // same email id
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[email protected]"));// whome u have to send mails that person id
message.setSubject("SUBJECT");
message.setText(" TEXT HERE ");
Transport.send(message);
//System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
@erjan
Copy link
Author

erjan commented Dec 12, 2017

THIS IS working & tested java code to send email programatically.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment