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