· 8 years ago · Aug 01, 2018, 11:40 AM
1import java.util.Properties;
2 import javax.mail.Message;
3 import javax.mail.MessagingException;
4 import javax.mail.PasswordAuthentication;
5 import javax.mail.Session;
6 import javax.mail.Transport;
7 import javax.mail.internet.InternetAddress;
8 import javax.mail.internet.MimeMessage;
9
10public class SendEmail {
11 public static void main(String[] args) {
12
13 final String username = "*****@gmail.com";
14 final String password = "******";
15
16 Properties props = new Properties();
17 props.put("mail.smtp.host", "smtp.gmail.com");
18 props.put("mail.smtp.socketFactory.port", "465");
19 props.put("mail.smtp.socketFactory.class",
20 "javax.net.ssl.SSLSocketFactory");
21 props.put("mail.smtp.auth", "true");
22 props.put("mail.smtp.port", "465");
23
24 Session session = Session.getDefaultInstance(props,
25 new javax.mail.Authenticator() {
26 protected PasswordAuthentication getPasswordAuthentication() {
27 return new PasswordAuthentication("username","password");
28 }
29 });
30
31 try {
32
33 Message message = new MimeMessage(session);
34 message.setFrom(new InternetAddress("from@no-spam.com"));
35 message.setRecipients(Message.RecipientType.TO,
36 InternetAddress.parse("to@no-spam.com"));
37 message.setSubject("Testing Subject");
38 message.setText("Dear Mail Crawler," +
39 "nn No spam to my email, please!");
40
41 Transport.send(message);
42
43 System.out.println("Done");
44
45 } catch (MessagingException e) {
46 throw new RuntimeException(e);
47 }
48}
49}