· 7 years ago · Dec 18, 2018, 04:32 PM
1public class SendEmailController {
2
3// private static String USER_NAME = ; // GMail user name (just the part before "@gmail.com")
4// private static String PASS = // GMail password
5 private static String RECIPIENT = "";
6
7 public static boolean send(String USERNAME, String pass) {
8 double time = 60.0;
9 String[] to = {RECIPIENT}; // list of recipient email addresses
10 String subject = "Bicycle locked";
11 String body = "Bicycle locked and taken for:" + time + "hours";
12
13 boolean b = sendFromGMail(USERNAME, pass, to, subject, body);
14 return b;
15 }
16
17 private static boolean sendFromGMail(String from, String pass, String[] to, String subject, String body) {
18 Properties props = System.getProperties();
19 String host = "smtp.gmail.com";
20 props.put("mail.smtp.starttls.enable", "true");
21 props.put("mail.smtp.host", host);
22 props.put("mail.smtp.user", from);
23 props.put("mail.smtp.password", pass);
24 props.put("mail.smtp.port", "587");
25 props.put("mail.smtp.auth", "true");
26
27 Session session = Session.getDefaultInstance(props);
28 MimeMessage message = new MimeMessage(session);
29 boolean b1 = true;
30
31 try {
32 message.setFrom(new InternetAddress(from));
33 InternetAddress[] toAddress = new InternetAddress[to.length];
34
35 // To get the array of addresses
36 for (int i = 0; i < to.length; i++) {
37 toAddress[i] = new InternetAddress(to[i]);
38 }
39
40 for (int i = 0; i < toAddress.length; i++) {
41 message.addRecipient(Message.RecipientType.TO, toAddress[i]);
42 }
43
44 message.setSubject(subject);
45 message.setText(body);
46 Transport transport = session.getTransport("smtp");
47 transport.connect(host, from, pass);
48 transport.sendMessage(message, message.getAllRecipients());
49 transport.close();
50 } catch (AddressException ae) {
51 ae.printStackTrace();
52 b1 = false;
53 } catch (MessagingException me) {
54 me.printStackTrace();
55 b1 = false;
56 } finally {
57 return b1;
58 }
59 }