· 8 years ago · Aug 20, 2017, 11:18 AM
1package com.boris.getandsend.service;
2
3
4import java.util.Properties;
5
6import javax.mail.Message;
7import javax.mail.MessagingException;
8import javax.mail.PasswordAuthentication;
9import javax.mail.Session;
10import javax.mail.Transport;
11import javax.mail.internet.InternetAddress;
12import javax.mail.internet.MimeMessage;
13
14import javax.activation.DataHandler;
15import javax.activation.DataSource;
16import javax.activation.FileDataSource;
17import javax.mail.BodyPart;
18
19import javax.mail.Multipart;
20
21import javax.mail.internet.MimeBodyPart;
22
23import javax.mail.internet.MimeMultipart;
24
25
26
27/**
28 * Created by boris on 02.08.17.
29 */
30public class SendMail {
31
32 private final String from = "********@gmail.com";
33 private final String username = "********";
34 private final String password = ************";
35
36 public void send (String to, String filename)
37 {
38
39 Properties props = new Properties();
40 props.put("mail.smtp.auth", "true");
41 props.put("mail.smtp.starttls.enable", "true");
42 props.put("mail.smtp.host", "smtp.gmail.com");
43 props.put("mail.smtp.port", "587");
44
45 Session session = Session.getInstance(props,
46 new javax.mail.Authenticator() {
47 protected PasswordAuthentication getPasswordAuthentication() {
48 return new PasswordAuthentication(username, password);
49 }
50 });
51
52 try {
53
54 // Create a default MimeMessage object.
55 Message message = new MimeMessage(session);
56
57 // Set From: header field of the header.
58 message.setFrom(new InternetAddress(from));
59
60 // Set To: header field of the header.
61 message.setRecipients(Message.RecipientType.TO,
62 InternetAddress.parse(to));
63
64 // Set Subject: header field
65 message.setSubject("This is the test");
66
67 // Create the message part
68 BodyPart messageBodyPart = new MimeBodyPart();
69
70 // Now set the actual message
71 messageBodyPart.setText("Yo! It works, right?");
72
73 // Create a multipar message
74 Multipart multipart = new MimeMultipart();
75
76 // Set text message part
77 multipart.addBodyPart(messageBodyPart);
78
79 // Part two is attachment
80 messageBodyPart = new MimeBodyPart();
81 DataSource source = new FileDataSource(filename);
82 messageBodyPart.setDataHandler(new DataHandler(source));
83 messageBodyPart.setFileName(filename);
84 multipart.addBodyPart(messageBodyPart);
85
86 // Send the complete message parts
87 message.setContent(multipart);
88
89 // Send message
90 Transport.send(message);
91
92 System.out.println("Sent message successfully....");
93
94 } catch (MessagingException e) {
95 throw new RuntimeException(e);
96 }
97
98
99 }
100
101}