· 6 years ago · Jan 25, 2020, 01:36 PM
1 private static String PASSWORD = ""; // GMail password
2 private static String USER_NAME = ""; // GMail user name (just the part before "@gmail.com")
3 private static String RECIPIENT = "9albert6@gmail.com";
4
5public static void main(String[] args) {
6 String from = USER_NAME;
7 String pass = PASSWORD;
8 String[] to = { RECIPIENT }; // list of recipient email addresses
9 String subject = "Java send mail example";
10 String body = "Welcome to JavaMail!";
11
12 sendFromGMail(from, pass, to, subject, body);
13 }
14
15private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
16 Properties props = System.getProperties();
17 String host = "smtp.gmail.com";
18 props.put("mail.smtp.starttls.enable", "true");
19 props.put("mail.smtp.host", host);
20 props.put("mail.smtp.user", from);
21 props.put("mail.smtp.password", pass);
22 props.put("mail.smtp.port", "587");
23 props.put("mail.smtp.auth", "true");
24
25 Session session = Session.getDefaultInstance(props);
26 MimeMessage message = new MimeMessage(session);
27
28 try {
29 message.setFrom(new InternetAddress(from));
30 InternetAddress[] toAddress = new InternetAddress[to.length];
31
32 // To get the array of addresses
33 for( int i = 0; i < to.length; i++ ) {
34 toAddress[i] = new InternetAddress(to[i]);
35 }
36
37 for( int i = 0; i < toAddress.length; i++) {
38 message.addRecipient(Message.RecipientType.TO, toAddress[i]);
39 }
40
41 message.setSubject(subject);
42 message.setText(body);
43 Transport transport = session.getTransport("smtp");
44 transport.connect(host, from, pass);
45 transport.sendMessage(message, message.getAllRecipients());
46 transport.close();
47 }
48 catch (AddressException ae) {
49 ae.printStackTrace();
50 }
51 catch (MessagingException me) {
52 me.printStackTrace();
53 }
54 }