-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEmailConverter.java
248 lines (223 loc) · 11.5 KB
/
EmailConverter.java
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
package peergos.email;
import org.simplejavamail.api.email.*;
import org.simplejavamail.converter.internal.mimemessage.MimeMessageParser;
import org.simplejavamail.email.EmailBuilder;
import peergos.shared.display.FileRef;
import peergos.shared.email.Attachment;
import peergos.shared.email.EmailMessage;
import peergos.shared.util.Pair;
import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;
import java.io.*;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.function.Supplier;
import java.util.stream.Collectors;
public class EmailConverter {
public static Pair<EmailMessage, List<RawAttachment>> parseMail(MimeMessage message, Supplier<String> messageIdSupplier) {
MimeMessageParser messageParser = new MimeMessageParser();
MimeMessageParser.ParsedMimeMessageComponents components = messageParser.parseMimeMessage(message);
String from = components.getFromAddress().getAddress();
String subject = components.getSubject();
List<String> toAddrs = components.getToAddresses().stream().map(a -> a.getAddress()).collect(Collectors.toList());
List<String> ccAddrs = components.getCcAddresses().stream().map(a -> a.getAddress()).collect(Collectors.toList());
String plainText = components.getPlainContent();
String messageId = components.getMessageId();
String msgId = messageId == null ? messageIdSupplier.get() : messageId;
Date sentDate = components.getSentDate();
LocalDateTime created = LocalDateTime.ofInstant(sentDate.toInstant(), ZoneId.of("UTC"));
List<RawAttachment> rawAttachmentList = new ArrayList<>();
for(Map.Entry<String, DataSource> attachment : components.getAttachmentList().entrySet()) {
DataSource source = attachment.getValue();
try {
String type = source.getContentType();
String name = source.getName();
String resName = attachment.getKey();
byte[] data = readResource(source.getInputStream());
rawAttachmentList.add(new RawAttachment(resName, data.length, type, data));
} catch(Exception e) {
e.printStackTrace();
}
}
//now embedded attachments
for(Map.Entry<String, DataSource> embeddedAttachments : components.getCidMap().entrySet()) {
DataSource source = embeddedAttachments.getValue();
try {
String type = source.getContentType();
String name = source.getName();
byte[] data = readResource(source.getInputStream());
rawAttachmentList.add(new RawAttachment(name, data.length, type, data));
} catch(Exception e) {
e.printStackTrace();
}
}
String calendarText = components.getCalendarContent();
if (calendarText == null) {
calendarText = "";
}
String id = UUID.randomUUID().toString();
EmailMessage emailMsg = new EmailMessage(id, msgId, from, subject, created,
toAddrs, ccAddrs, Collections.emptyList(),
plainText, true, false, Collections.emptyList(), calendarText,
Optional.empty(), Optional.empty(), Optional.empty());
return new Pair<>(emailMsg, rawAttachmentList);
}
private static byte[] readResource(InputStream in) throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
OutputStream gout = new DataOutputStream(bout);
byte[] tmp = new byte[4096];
int r;
while ((r=in.read(tmp)) >= 0)
gout.write(tmp, 0, r);
gout.flush();
gout.close();
in.close();
return bout.toByteArray();
}
private static String formatAddressList(List<Recipient> recipients) {
return recipients.stream().map(r -> r.getAddress()).collect(Collectors.joining(", "));
}
/*
See https://javaee.github.io/javamail/FAQ#forward for options
using EmailBuilder.forwarding(origEmail) produces option 1 which doesn't feel right (especially for attachments)
so going with option 2 - forward the message "inline"
*/
private static EmailPopulatingBuilder buildForwardEmail(Email forwardedEmail) {
EmailPopulatingBuilder builder = null;
if (false) {
//builder = EmailBuilder.forwarding(origEmail);
} else {
builder = EmailBuilder.startingBlank();
String plainText = forwardedEmail.getPlainText();
String forwardedText = String.format(
"\n\n-------- Original Message --------\n" + "Subject: %s\nDate: %s\nFrom: %s\nTo: %s\n",
forwardedEmail.getSubject(),
forwardedEmail.getSentDate(),
forwardedEmail.getFromRecipient().getAddress(),
formatAddressList(
forwardedEmail.getRecipients().stream()
.filter(r -> r.getType() == javax.mail.Message.RecipientType.TO)
.collect(Collectors.toList()))
);
builder = builder.withPlainText(forwardedText + "\n" + plainText);
builder = builder.withAttachments(forwardedEmail.getAttachments());
}
return builder;
}
private static String buildAttachmentUUIDMapKey(String name, int length, String type) {
return name + "-" + length + "-" + type;
}
private static Map<String, String> populateAttachmentUUIDMap(EmailMessage email, Map<String, byte[]> attachmentsMap) {
Map<String, String> attachmentToUUIDMap = new HashMap<>();
populateAttachmentUUIDMap(email.attachments, attachmentsMap, attachmentToUUIDMap);
if (email.forwardingToEmail.isPresent()) {
populateAttachmentUUIDMap(email.forwardingToEmail.get().attachments, attachmentsMap, attachmentToUUIDMap);
}
return attachmentToUUIDMap;
}
private static void populateAttachmentUUIDMap(List<Attachment> attachments, Map<String, byte[]> attachmentsMap,
Map<String, String> attachmentToUUIDMap) {
for(Attachment attachment : attachments) {
byte[] val = attachmentsMap.get(attachment.uuid);
if (val != null) {
String key = buildAttachmentUUIDMapKey(attachment.filename, val.length, attachment.type);
attachmentToUUIDMap.put(key, attachment.uuid);
}
}
}
public static Pair<Email, Optional<EmailMessage>> toEmail(EmailMessage email, Map<String, byte[]> attachmentsMap, boolean roundTrip) {
Map<String, String> attachmentToUUIDMap = populateAttachmentUUIDMap(email, attachmentsMap);
Collection<Recipient> toAddrs = email.to.stream()
.map(a -> new Recipient(null, a, Message.RecipientType.TO))
.collect(Collectors.toList());
Collection<Recipient> ccAddrs = email.cc.stream()
.map(a -> new Recipient(null, a, Message.RecipientType.TO))
.collect(Collectors.toList());
Collection<Recipient> bccAddrs = email.bcc.stream()
.map(a -> new Recipient(null, a, Message.RecipientType.TO))
.collect(Collectors.toList());
EmailPopulatingBuilder builder = null;
//https://www.simplejavamail.org/features.html#section-reply-forward
if(email.replyingToEmail.isPresent()) {
Email origEmail = toEmail(email.replyingToEmail.get(), attachmentsMap, false).left;
builder = EmailBuilder.replyingTo(origEmail);
} else if(email.forwardingToEmail.isPresent()) {
Email origEmail = toEmail(email.forwardingToEmail.get(), attachmentsMap, false).left;
builder = buildForwardEmail(origEmail);
} else {
builder = EmailBuilder.startingBlank();
}
builder = builder.fixingMessageId(email.msgId)
.clearRecipients()
.from(email.from)
.to(toAddrs)
.cc(ccAddrs)
.bcc(bccAddrs);
if (email.replyingToEmail.isPresent()) {
builder = builder.prependText(email.content + "\n\n");
} else if (email.forwardingToEmail.isPresent()) {
builder = builder.prependText(email.content);
} else {
builder = builder.withPlainText(email.content);
}
builder = builder.withSubject(email.subject);
Date sendDate = Date.from(email.created.atZone(ZoneId.of("UTC")).toInstant());
builder = builder.fixingSentDate(sendDate);
if (email.icalEvent.length() > 0) {
CalendarMethod method = email.subject.startsWith("CANCELLED") ? CalendarMethod.CANCEL : CalendarMethod.REQUEST;
builder = builder.withCalendarText(method, email.icalEvent);
}
List<AttachmentResource> emailAttachments = email.attachments.stream()
.filter(f -> attachmentsMap.containsKey(f.uuid))
.map(a -> new AttachmentResource(a.filename, new ByteArrayDataSource(attachmentsMap.get(a.uuid), a.type)))
.collect(Collectors.toList());
if (emailAttachments.size() > 0) {
builder = builder.withAttachments(emailAttachments);
}
Email producedEmail = builder.buildEmail();
Optional<EmailMessage> emailMessage = roundTrip ?
Optional.of(toSentEmailMessage(email.id, producedEmail, attachmentToUUIDMap)) : Optional.empty();
return new Pair<>(producedEmail, emailMessage);
}
private static EmailMessage toSentEmailMessage(String id, Email email, Map<String, String> attachmentToUUIDMap) {
List<Attachment> attachments = new ArrayList<>();
for(AttachmentResource res : email.getAttachments()) {
DataSource source = res.getDataSource();
try {
String type = source.getContentType();
String name = res.getName();
byte[] data = readResource(source.getInputStream());
String key = buildAttachmentUUIDMapKey(name, data.length, type);
Attachment attachment = new Attachment(name, data.length, type, attachmentToUUIDMap.get(key));
attachments.add(attachment);
} catch(Exception e) {
}
}
String calendarText = email.getCalendarText();
Recipient from = email.getFromRecipient();
String msgId = email.getId();
String plainText = email.getPlainText();
Date sentDate = email.getSentDate();
LocalDateTime created = LocalDateTime.ofInstant(sentDate.toInstant(), ZoneId.of("UTC"));
String subject = email.getSubject();
List<Recipient> recipients = email.getRecipients();
List<String> toAddrs = new ArrayList<>();
List<String> ccAddrs = new ArrayList<>();
List<String> bccAddrs = new ArrayList<>();
for(Recipient person : recipients) {
if (person.getType() == Message.RecipientType.TO) {
toAddrs.add(person.getAddress());
} else if(person.getType() == Message.RecipientType.CC) {
ccAddrs.add(person.getAddress());
} else if(person.getType() == Message.RecipientType.BCC) {
bccAddrs.add(person.getAddress());
}
}
return new EmailMessage(id, msgId, from.getAddress(), subject, created,
toAddrs, ccAddrs, bccAddrs, plainText, true, false, attachments, calendarText,
Optional.empty(), Optional.empty(), Optional.empty());
}
}