-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMailService.java
More file actions
157 lines (149 loc) · 7.57 KB
/
MailService.java
File metadata and controls
157 lines (149 loc) · 7.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
package test.Email;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.Base64;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Paths;
import java.util.*;
public class MailService {
private static final Logger LOGGER = LoggerFactory.getLogger(EmailTest.class);
private static final String APPLICATION_NAME = "First Tech India";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final String TOKENS_DIRECTORY_PATH = "tokens";
private static final List<String> SCOPES = Collections.singletonList(GmailScopes.MAIL_GOOGLE_COM);
private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
private boolean check = false;
Session getSession(String fromEmail, String password) {
Properties props = new Properties();
if (!password.equals("")) {
check = true;
LOGGER.info("Started getting the session with props");
props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
props.put("mail.smtp.socketFactory.port", "465"); //SSL Port
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory"); //SSL Factory Class
props.put("mail.smtp.auth", "true"); //Enabling SMTP Authentication
props.put("mail.smtp.port", "465"); //SMTP Port
Authenticator auth = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};
return Session.getDefaultInstance(props, auth);
}else {
LOGGER.info("Started getting the session without props");
return Session.getDefaultInstance(props, null);
}
}
List zipAndGetAllFiles(MailConfig mailConfig,String currentPath) {
String[] zipDestinationFolders = mailConfig.getValue("zip.destination.folders").split(",");
String zipSourceFolders= mailConfig.getValue("zip.source.folders");
int i = 0;
List files = new ArrayList();
LOGGER.info("Zip for folders {} to {} is started ", zipSourceFolders,zipDestinationFolders);
for (String zipSourceFolder : zipSourceFolders.split(",")) {
ZipReport zipReport = new ZipReport();
zipReport.zipFolder(Paths.get(currentPath.concat(zipSourceFolder))
, Paths.get(currentPath.concat(zipDestinationFolders[i])));
files.add(currentPath.concat(zipDestinationFolders[i]));
i++;
}
String fileNames = mailConfig.getValue("file.location");
LOGGER.info("Attaching all the files {} to {} ", fileNames,files);
for(String fileName : fileNames.split(",")){
files.add(currentPath.concat(fileName));
}
return files;
}
void sendEmail(Session session, String toEmail,String fromEmail, String subject, String body , List fileNames){
try
{
LOGGER.info("Sending mail to {} ",toEmail);
MimeMessage msg = new MimeMessage(session);
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setSubject(subject, "UTF-8");
msg.setSentDate(new Date());
msg.setFrom(new InternetAddress(fromEmail));
msg.addRecipient(javax.mail.Message.RecipientType.TO,
new InternetAddress(toEmail));
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(body);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
LOGGER.debug("Started adding files {} to mail ",fileNames);
for(Object fileName : fileNames) {
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource((String)fileName);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName((String)fileName);
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);
}
LOGGER.info("Message has been prepaired to send");
if(check){
Transport.send(msg);
}else {
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
Gmail service = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
Message message = createMessageWithEmail(msg);
message = service.users().messages().send(toEmail, message).execute();
LOGGER.debug("Output Message Details{}", message.toPrettyString());
}
System.out.println("EMail Sent Successfully with attachment!!");
}
catch (Exception e) {
e.printStackTrace();
}
}
public Message createMessageWithEmail(MimeMessage emailContent)
throws MessagingException, IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
LOGGER.info("Converting message to send in mail");
emailContent.writeTo(buffer);
byte[] bytes = buffer.toByteArray();
String encodedEmail = Base64.encodeBase64URLSafeString(bytes);
Message message = new Message();
message.setRaw(encodedEmail);
return message;
}
private Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
// Load client secrets.
InputStream in = EmailTest.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
}