· 9 years ago · Mar 03, 2017, 03:24 PM
1import java.util.*;
2import javax.mail.*;
3import javax.mail.internet.*;
4
5
6public class SendEmail {
7
8 public static void main(String [] args) {
9 Properties properties = new Properties();
10 properties.put("mail.smtp.host", "smtp.gmail.com");
11 properties.put("mail.smtp.socketFactory.port","465");
12 properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
13 properties.put("mail.smtp.auth", "true");
14 properties.put("mail.smtp.port","465");
15 // Recipient's email ID needs to be mentioned.
16 String to = "*****@gmail.com";
17 // Sender's email ID needs to be mentioned
18 String from = "******@gmail.com";
19
20 Session session = Session.getDefaultInstance(properties,
21 new Authenticator() {
22 @Override
23 protected PasswordAuthentication getPasswordAuthentication() {
24 return new PasswordAuthentication("***@gmail.com","******");
25 }
26 });
27
28 try {
29 // Create a default MimeMessage object.
30 MimeMessage message = new MimeMessage(session);
31
32 // Set From: header field of the header.
33 message.setFrom(new InternetAddress(from));
34
35 // Set To: header field of the header.
36 message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
37
38 // Set Subject: header field
39 message.setSubject("This is the Subject Line!");
40
41 // Now set the actual message
42 message.setText("This is actual message");
43
44 // Send message
45 Transport.send(message);
46 System.out.println("Sent message successfully....");
47 }catch (MessagingException mex) {
48 mex.printStackTrace();
49 }
50 }
51}