Files
FairEmail/app/src/main/java/eu/faircode/email/MessageHelper.java

1129 lines
44 KiB
Java
Raw Normal View History

2018-08-02 13:33:06 +00:00
package eu.faircode.email;
/*
2018-08-14 05:53:24 +00:00
This file is part of FairEmail.
2018-08-02 13:33:06 +00:00
2018-08-14 05:53:24 +00:00
FairEmail is free software: you can redistribute it and/or modify
2018-08-02 13:33:06 +00:00
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2018-10-29 10:46:49 +00:00
FairEmail is distributed in the hope that it will be useful,
2018-08-02 13:33:06 +00:00
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
2018-10-29 10:46:49 +00:00
along with FairEmail. If not, see <http://www.gnu.org/licenses/>.
2018-08-02 13:33:06 +00:00
2018-12-31 08:04:33 +00:00
Copyright 2018-2019 by Marcel Bokhorst (M66B)
2018-08-02 13:33:06 +00:00
*/
2018-08-13 08:58:36 +00:00
import android.content.Context;
2019-05-21 14:50:10 +02:00
import android.net.MailTo;
2018-08-02 13:33:06 +00:00
import android.text.TextUtils;
2018-09-05 07:57:34 +00:00
import android.webkit.MimeTypeMap;
2018-08-02 13:33:06 +00:00
2019-04-25 20:40:37 +02:00
import com.sun.mail.util.FolderClosedIOException;
2019-06-02 07:58:43 +02:00
import com.sun.mail.util.MessageRemovedIOException;
2019-04-25 20:40:37 +02:00
2019-01-16 10:57:57 +00:00
import java.io.BufferedOutputStream;
2018-10-28 14:29:45 +00:00
import java.io.BufferedReader;
2018-08-02 13:33:06 +00:00
import java.io.ByteArrayOutputStream;
2018-08-13 08:58:36 +00:00
import java.io.File;
2019-01-16 10:57:57 +00:00
import java.io.FileOutputStream;
2018-10-28 14:29:45 +00:00
import java.io.FileReader;
2018-08-02 13:33:06 +00:00
import java.io.IOException;
import java.io.InputStream;
2019-01-16 10:57:57 +00:00
import java.io.OutputStream;
2018-08-22 15:13:01 +00:00
import java.io.UnsupportedEncodingException;
2018-08-11 06:50:21 +00:00
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
2018-08-02 13:33:06 +00:00
import java.util.ArrayList;
import java.util.Date;
2019-01-25 09:37:43 +00:00
import java.util.Enumeration;
2018-08-02 13:33:06 +00:00
import java.util.List;
2019-06-26 21:21:09 +02:00
import java.util.Objects;
2018-08-02 13:33:06 +00:00
import java.util.Properties;
2019-06-14 17:25:54 +02:00
import java.util.TimeZone;
2018-08-02 13:33:06 +00:00
2018-08-11 06:50:21 +00:00
import javax.activation.DataHandler;
2018-08-13 08:58:36 +00:00
import javax.activation.FileDataSource;
import javax.activation.FileTypeMap;
2018-08-02 13:33:06 +00:00
import javax.mail.Address;
2018-08-03 12:07:51 +00:00
import javax.mail.BodyPart;
2018-08-02 13:33:06 +00:00
import javax.mail.Flags;
import javax.mail.FolderClosedException;
2019-01-25 09:37:43 +00:00
import javax.mail.Header;
2018-08-02 13:33:06 +00:00
import javax.mail.Message;
import javax.mail.MessageRemovedException;
2018-08-02 13:33:06 +00:00
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
2019-01-19 19:08:01 +00:00
import javax.mail.internet.AddressException;
2018-08-03 12:07:51 +00:00
import javax.mail.internet.ContentType;
2018-08-02 13:33:06 +00:00
import javax.mail.internet.InternetAddress;
2019-06-14 17:25:54 +02:00
import javax.mail.internet.MailDateFormat;
2018-08-11 06:50:21 +00:00
import javax.mail.internet.MimeBodyPart;
2018-08-02 13:33:06 +00:00
import javax.mail.internet.MimeMessage;
2018-08-11 06:50:21 +00:00
import javax.mail.internet.MimeMultipart;
2019-01-01 14:58:51 +01:00
import javax.mail.internet.MimeUtility;
2018-09-06 10:24:30 +00:00
import javax.mail.internet.ParseException;
2018-08-02 13:33:06 +00:00
2019-05-18 19:44:21 +02:00
import biweekly.Biweekly;
import biweekly.ICalendar;
2018-08-02 13:33:06 +00:00
public class MessageHelper {
private MimeMessage imessage;
2019-04-24 10:22:54 +02:00
private final static int CONNECT_TIMEOUT = 20 * 1000; // milliseconds
private final static int WRITE_TIMEOUT = 40 * 1000; // milliseconds
private final static int READ_TIMEOUT = 40 * 1000; // milliseconds
2019-05-23 18:27:43 +02:00
private final static int FETCH_SIZE = 256 * 1024; // bytes, default 16K
2019-01-31 18:35:37 +00:00
private final static int POOL_TIMEOUT = 45 * 1000; // milliseconds, default 45 sec
2018-09-08 18:03:10 +00:00
private static final int APPEND_BUFFER_SIZE = 4 * 1024 * 1024; // bytes
2019-01-16 10:57:57 +00:00
static final int ATTACHMENT_BUFFER_SIZE = 8192; // bytes
static final int DEFAULT_ATTACHMENT_DOWNLOAD_SIZE = 65536; // bytes
2019-01-16 10:57:57 +00:00
2019-02-06 13:51:41 +00:00
static void setSystemProperties() {
System.setProperty("mail.mime.decodetext.strict", "false");
System.setProperty("mail.mime.ignoreunknownencoding", "true"); // Content-Transfer-Encoding
System.setProperty("mail.mime.base64.ignoreerrors", "true");
System.setProperty("mail.mime.decodefilename", "true");
System.setProperty("mail.mime.encodefilename", "true");
2019-02-17 10:47:50 +00:00
System.setProperty("mail.mime.allowutf8", "false"); // InternetAddress, MimeBodyPart, MimeUtility
2019-06-14 17:12:05 +02:00
System.setProperty("mail.mime.cachemultipart", "false");
2019-02-06 13:51:41 +00:00
// https://docs.oracle.com/javaee/6/api/javax/mail/internet/MimeMultipart.html
System.setProperty("mail.mime.multipart.ignoremissingboundaryparameter", "true"); // javax.mail.internet.ParseException: In parameter list
System.setProperty("mail.mime.multipart.ignoreexistingboundaryparameter", "true");
}
2019-06-19 14:51:19 +02:00
static Properties getSessionProperties(String realm, boolean insecure) {
2018-08-02 13:33:06 +00:00
Properties props = new Properties();
props.put("mail.event.scope", "folder");
2018-10-23 07:52:20 +00:00
String checkserveridentity = Boolean.toString(!insecure).toLowerCase();
2018-08-02 13:33:06 +00:00
// https://javaee.github.io/javamail/docs/api/com/sun/mail/imap/package-summary.html#properties
2018-10-23 07:52:20 +00:00
props.put("mail.imaps.ssl.checkserveridentity", checkserveridentity);
2018-08-08 06:55:47 +00:00
props.put("mail.imaps.ssl.trust", "*");
props.put("mail.imaps.starttls.enable", "false");
2019-01-10 18:24:20 +00:00
if (realm != null)
props.put("mail.imaps.auth.ntlm.domain", realm);
2018-08-15 16:58:27 +00:00
// TODO: make timeouts configurable?
2019-04-24 10:22:54 +02:00
props.put("mail.imaps.connectiontimeout", Integer.toString(CONNECT_TIMEOUT));
props.put("mail.imaps.writetimeout", Integer.toString(WRITE_TIMEOUT)); // one thread overhead
props.put("mail.imaps.timeout", Integer.toString(READ_TIMEOUT));
2018-08-02 13:33:06 +00:00
2018-09-11 16:29:04 +00:00
props.put("mail.imaps.connectionpool.debug", "true");
props.put("mail.imaps.connectionpoolsize", "2");
props.put("mail.imaps.connectionpooltimeout", Integer.toString(POOL_TIMEOUT));
props.put("mail.imaps.finalizecleanclose", "false");
// https://tools.ietf.org/html/rfc4978
// https://docs.oracle.com/javase/8/docs/api/java/util/zip/Deflater.html
2018-10-23 07:52:20 +00:00
props.put("mail.imaps.compress.enable", "true");
//props.put("mail.imaps.compress.level", "-1");
//props.put("mail.imaps.compress.strategy", "0");
2019-01-07 08:15:27 +00:00
props.put("mail.imaps.throwsearchexception", "true");
props.put("mail.imaps.fetchsize", Integer.toString(FETCH_SIZE));
2018-10-07 09:49:22 +00:00
props.put("mail.imaps.peek", "true");
props.put("mail.imaps.appendbuffersize", Integer.toString(APPEND_BUFFER_SIZE));
2018-10-23 07:52:20 +00:00
props.put("mail.imap.ssl.checkserveridentity", checkserveridentity);
props.put("mail.imap.ssl.trust", "*");
props.put("mail.imap.starttls.enable", "true");
props.put("mail.imap.starttls.required", "true");
2019-01-10 18:24:20 +00:00
if (realm != null)
props.put("mail.imap.auth.ntlm.domain", realm);
2018-10-23 07:52:20 +00:00
2019-04-24 10:22:54 +02:00
props.put("mail.imap.connectiontimeout", Integer.toString(CONNECT_TIMEOUT));
props.put("mail.imap.writetimeout", Integer.toString(WRITE_TIMEOUT)); // one thread overhead
props.put("mail.imap.timeout", Integer.toString(READ_TIMEOUT));
2018-10-23 07:52:20 +00:00
props.put("mail.imap.connectionpool.debug", "true");
props.put("mail.imap.connectionpoolsize", "2");
props.put("mail.imap.connectionpooltimeout", Integer.toString(POOL_TIMEOUT));
2018-10-23 07:52:20 +00:00
props.put("mail.imap.finalizecleanclose", "false");
2018-10-23 07:52:20 +00:00
props.put("mail.imap.compress.enable", "true");
2019-01-07 08:15:27 +00:00
props.put("mail.imap.throwsearchexception", "true");
props.put("mail.imap.fetchsize", Integer.toString(FETCH_SIZE));
2018-10-23 07:52:20 +00:00
props.put("mail.imap.peek", "true");
props.put("mail.imap.appendbuffersize", Integer.toString(APPEND_BUFFER_SIZE));
2018-10-23 07:52:20 +00:00
2018-08-15 16:58:27 +00:00
// https://javaee.github.io/javamail/docs/api/com/sun/mail/smtp/package-summary.html#properties
2018-10-23 07:52:20 +00:00
props.put("mail.smtps.ssl.checkserveridentity", checkserveridentity);
2018-08-08 06:55:47 +00:00
props.put("mail.smtps.ssl.trust", "*");
props.put("mail.smtps.starttls.enable", "false");
props.put("mail.smtps.starttls.required", "false");
2019-01-10 18:24:20 +00:00
2018-08-08 06:55:47 +00:00
props.put("mail.smtps.auth", "true");
2019-01-10 18:24:20 +00:00
if (realm != null)
props.put("mail.smtps.auth.ntlm.domain", realm);
2018-08-15 16:58:27 +00:00
2019-04-24 10:22:54 +02:00
props.put("mail.smtps.connectiontimeout", Integer.toString(CONNECT_TIMEOUT));
props.put("mail.smtps.writetimeout", Integer.toString(WRITE_TIMEOUT)); // one thread overhead
props.put("mail.smtps.timeout", Integer.toString(READ_TIMEOUT));
2018-08-08 06:55:47 +00:00
2018-10-23 07:52:20 +00:00
props.put("mail.smtp.ssl.checkserveridentity", checkserveridentity);
2018-08-08 06:55:47 +00:00
props.put("mail.smtp.ssl.trust", "*");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true");
2019-01-10 18:24:20 +00:00
2018-08-08 06:55:47 +00:00
props.put("mail.smtp.auth", "true");
2019-01-10 18:24:20 +00:00
if (realm != null)
props.put("mail.smtp.auth.ntlm.domain", realm);
2018-08-15 16:58:27 +00:00
2019-04-24 10:22:54 +02:00
props.put("mail.smtp.connectiontimeout", Integer.toString(CONNECT_TIMEOUT));
props.put("mail.smtp.writetimeout", Integer.toString(WRITE_TIMEOUT)); // one thread overhead
props.put("mail.smtp.timeout", Integer.toString(READ_TIMEOUT));
2018-08-02 13:33:06 +00:00
2019-02-09 21:03:53 +00:00
// MIME
2019-02-17 10:47:50 +00:00
props.put("mail.mime.allowutf8", "false"); // SMTPTransport, MimeMessage
2018-08-26 12:17:09 +00:00
props.put("mail.mime.address.strict", "false");
2018-09-16 14:01:18 +00:00
2018-09-21 13:18:26 +00:00
if (false) {
2018-12-24 12:27:45 +00:00
Log.i("Prefering IPv4");
System.setProperty("java.net.preferIPv4Stack", "true");
}
2018-09-17 16:21:17 +00:00
2018-08-02 13:33:06 +00:00
return props;
}
2019-04-17 17:27:57 +02:00
static MimeMessageEx from(Context context, EntityMessage message, EntityIdentity identity, Session isession)
throws MessagingException, IOException {
DB db = DB.getInstance(context);
MimeMessageEx imessage = new MimeMessageEx(isession, message.msgid);
2018-08-02 13:33:06 +00:00
2019-01-21 16:45:05 +00:00
if (message.references != null)
imessage.addHeader("References", message.references);
if (message.inreplyto != null)
imessage.addHeader("In-Reply-To", message.inreplyto);
imessage.addHeader("X-FairEmail-ID", message.msgid);
2018-11-20 16:51:51 +01:00
2018-08-11 17:31:33 +00:00
imessage.setFlag(Flags.Flag.SEEN, message.seen);
2019-01-24 07:11:41 +00:00
imessage.setFlag(Flags.Flag.FLAGGED, message.flagged);
imessage.setFlag(Flags.Flag.ANSWERED, message.answered);
2018-08-11 17:31:33 +00:00
2018-11-09 07:22:44 +00:00
if (message.from != null && message.from.length > 0) {
String email = ((InternetAddress) message.from[0]).getAddress();
String name = ((InternetAddress) message.from[0]).getPersonal();
2019-04-17 17:27:57 +02:00
if (email != null && identity != null && identity.sender_extra && !TextUtils.isEmpty(message.extra)) {
2018-11-09 07:22:44 +00:00
int at = email.indexOf('@');
2019-02-13 08:08:40 +00:00
email = message.extra + email.substring(at);
2018-12-24 12:27:45 +00:00
Log.i("extra=" + email);
2018-11-09 07:22:44 +00:00
}
imessage.setFrom(new InternetAddress(email, name));
}
2018-08-02 13:33:06 +00:00
if (message.to != null && message.to.length > 0)
imessage.setRecipients(Message.RecipientType.TO, message.to);
2018-08-02 13:33:06 +00:00
if (message.cc != null && message.cc.length > 0)
imessage.setRecipients(Message.RecipientType.CC, message.cc);
2018-08-03 07:39:43 +00:00
if (message.bcc != null && message.bcc.length > 0)
imessage.setRecipients(Message.RecipientType.BCC, message.bcc);
2018-08-02 13:33:06 +00:00
if (message.subject != null)
imessage.setSubject(message.subject);
2019-06-14 17:25:54 +02:00
MailDateFormat mdf = new MailDateFormat();
mdf.setTimeZone(TimeZone.getTimeZone("UTC"));
imessage.setHeader("Date", mdf.format(new Date()));
//imessage.setSentDate(new Date());
2018-10-28 12:49:13 +00:00
List<EntityAttachment> attachments = db.attachment().getAttachments(message.id);
2018-10-28 14:29:45 +00:00
if (message.from != null && message.from.length > 0)
for (EntityAttachment attachment : attachments)
2019-01-05 14:09:47 +00:00
if (attachment.available && EntityAttachment.PGP_SIGNATURE.equals(attachment.encryption)) {
2018-10-28 14:29:45 +00:00
InternetAddress from = (InternetAddress) message.from[0];
2019-03-14 07:18:42 +00:00
File file = attachment.getFile(context);
2018-10-28 14:29:45 +00:00
StringBuilder sb = new StringBuilder();
2019-02-22 16:59:23 +01:00
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
2018-10-28 14:29:45 +00:00
String line;
while ((line = br.readLine()) != null)
if (!line.startsWith("-----") && !line.endsWith("-----"))
sb.append(line);
}
imessage.addHeader("Autocrypt", "addr=" + from.getAddress() + "; keydata=" + sb.toString());
}
2018-10-28 12:49:13 +00:00
for (final EntityAttachment attachment : attachments)
2019-01-05 14:09:47 +00:00
if (attachment.available && EntityAttachment.PGP_MESSAGE.equals(attachment.encryption)) {
2018-10-28 12:49:13 +00:00
Multipart multipart = new MimeMultipart("encrypted; protocol=\"application/pgp-encrypted\"");
BodyPart pgp = new MimeBodyPart();
pgp.setContent("", "application/pgp-encrypted");
multipart.addBodyPart(pgp);
BodyPart bpAttachment = new MimeBodyPart();
bpAttachment.setFileName(attachment.name);
2019-03-14 07:18:42 +00:00
File file = attachment.getFile(context);
2018-10-28 12:49:13 +00:00
FileDataSource dataSource = new FileDataSource(file);
dataSource.setFileTypeMap(new FileTypeMap() {
@Override
public String getContentType(File file) {
return attachment.type;
}
@Override
public String getContentType(String filename) {
return attachment.type;
}
});
bpAttachment.setDataHandler(new DataHandler(dataSource));
bpAttachment.setDisposition(Part.INLINE);
multipart.addBodyPart(bpAttachment);
imessage.setContent(multipart);
return imessage;
}
2018-08-11 07:20:42 +00:00
2019-04-23 21:21:06 +02:00
build(context, message, attachments, identity, imessage);
2018-10-29 09:13:29 +00:00
return imessage;
}
2019-04-23 21:21:06 +02:00
static void build(Context context, EntityMessage message, List<EntityAttachment> attachments, EntityIdentity identity, MimeMessage imessage) throws IOException, MessagingException {
2019-04-18 19:13:38 +02:00
if (message.receipt_request != null && message.receipt_request) {
// https://www.ietf.org/rfc/rfc3798.txt
Multipart report = new MimeMultipart("report; report-type=disposition-notification");
String plainContent = HtmlHelper.getText(Helper.readText(message.getFile(context)));
BodyPart plainPart = new MimeBodyPart();
plainPart.setContent(plainContent, "text/plain; charset=" + Charset.defaultCharset().name());
report.addBodyPart(plainPart);
BodyPart dnsPart = new MimeBodyPart();
dnsPart.setContent("", "message/disposition-notification; name=\"MDNPart2.txt\"");
dnsPart.setDisposition(Part.INLINE);
report.addBodyPart(dnsPart);
//BodyPart headersPart = new MimeBodyPart();
//headersPart.setContent("", "text/rfc822-headers; name=\"MDNPart3.txt\"");
//headersPart.setDisposition(Part.INLINE);
//report.addBodyPart(headersPart);
imessage.setContent(report);
return;
}
2018-12-16 16:39:25 +01:00
StringBuilder body = new StringBuilder();
2019-03-14 07:45:13 +00:00
body.append(Helper.readText(message.getFile(context)));
2018-09-26 12:22:10 +00:00
2019-04-17 17:27:57 +02:00
if (identity != null && !TextUtils.isEmpty(identity.signature))
body.append(identity.signature);
2019-03-14 07:45:13 +00:00
File refFile = message.getRefFile(context);
2019-01-21 16:45:05 +00:00
if (refFile.exists())
body.append(Helper.readText(refFile));
2019-01-06 13:51:38 +00:00
String plainContent = HtmlHelper.getText(body.toString());
StringBuilder htmlContent = new StringBuilder();
htmlContent.append(body.toString()).append("\n");
BodyPart plainPart = new MimeBodyPart();
plainPart.setContent(plainContent, "text/plain; charset=" + Charset.defaultCharset().name());
BodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(htmlContent.toString(), "text/html; charset=" + Charset.defaultCharset().name());
Multipart alternativePart = new MimeMultipart("alternative");
alternativePart.addBodyPart(plainPart);
alternativePart.addBodyPart(htmlPart);
2019-01-11 18:54:55 +00:00
int available = 0;
for (EntityAttachment attachment : attachments)
if (attachment.available)
available++;
Log.i("Attachments available=" + available);
if (available == 0)
2019-05-04 20:52:21 +02:00
if (message.plain_only != null && message.plain_only)
imessage.setContent(plainContent, "text/plain; charset=" + Charset.defaultCharset().name());
else
imessage.setContent(alternativePart);
2019-01-06 13:51:38 +00:00
else {
Multipart mixedPart = new MimeMultipart("mixed");
2018-08-11 06:50:21 +00:00
2019-01-06 13:51:38 +00:00
BodyPart attachmentPart = new MimeBodyPart();
2019-05-04 20:52:21 +02:00
if (message.plain_only != null && message.plain_only)
attachmentPart.setContent(plainContent, "text/plain; charset=" + Charset.defaultCharset().name());
else
attachmentPart.setContent(alternativePart);
2019-01-06 13:51:38 +00:00
mixedPart.addBodyPart(attachmentPart);
2018-08-11 06:50:21 +00:00
2018-08-13 08:58:36 +00:00
for (final EntityAttachment attachment : attachments)
2018-08-19 06:53:56 +00:00
if (attachment.available) {
2018-08-13 08:58:36 +00:00
BodyPart bpAttachment = new MimeBodyPart();
2019-03-14 07:18:42 +00:00
File file = attachment.getFile(context);
2019-05-18 19:44:21 +02:00
2018-08-13 08:58:36 +00:00
FileDataSource dataSource = new FileDataSource(file);
dataSource.setFileTypeMap(new FileTypeMap() {
@Override
public String getContentType(File file) {
2019-05-18 19:44:21 +02:00
// https://tools.ietf.org/html/rfc6047
if ("text/calendar".equals(attachment.type))
try {
ICalendar icalendar = Biweekly.parse(file).first();
if (icalendar != null &&
icalendar.getMethod() != null &&
icalendar.getMethod().isReply())
return "text/calendar" +
"; method=REPLY" +
"; charset=" + Charset.defaultCharset().name();
} catch (IOException ex) {
Log.e(ex);
}
2018-08-13 08:58:36 +00:00
return attachment.type;
}
@Override
public String getContentType(String filename) {
2019-05-18 19:44:21 +02:00
return getContentType(new File(filename));
2018-08-13 08:58:36 +00:00
}
});
bpAttachment.setDataHandler(new DataHandler(dataSource));
2019-05-18 19:44:21 +02:00
bpAttachment.setFileName(attachment.name);
if (attachment.disposition != null)
bpAttachment.setDisposition(attachment.disposition);
2018-09-13 18:31:05 +00:00
if (attachment.cid != null)
bpAttachment.setHeader("Content-ID", attachment.cid);
2018-08-13 08:58:36 +00:00
2019-01-06 13:51:38 +00:00
mixedPart.addBodyPart(bpAttachment);
2018-08-13 08:58:36 +00:00
}
2018-08-11 06:50:21 +00:00
2019-01-06 13:51:38 +00:00
imessage.setContent(mixedPart);
2018-08-11 06:50:21 +00:00
}
2018-08-02 13:33:06 +00:00
}
MessageHelper(MimeMessage message) {
this.imessage = message;
}
2018-08-03 12:07:51 +00:00
boolean getSeen() throws MessagingException {
return imessage.isSet(Flags.Flag.SEEN);
}
2018-11-24 19:14:28 +01:00
boolean getAnsered() throws MessagingException {
return imessage.isSet(Flags.Flag.ANSWERED);
}
2018-09-07 15:12:43 +00:00
boolean getFlagged() throws MessagingException {
return imessage.isSet(Flags.Flag.FLAGGED);
}
2019-01-29 20:15:24 +00:00
String getFlags() throws MessagingException {
if (!BuildConfig.DEBUG)
return null;
Flags flags = imessage.getFlags();
flags.clearUserFlags();
return flags.toString();
}
2018-11-25 13:34:08 +01:00
String[] getKeywords() throws MessagingException {
return imessage.getFlags().getUserFlags();
}
2018-08-02 13:33:06 +00:00
String getMessageID() throws MessagingException {
// Outlook outbox -> sent
2019-05-03 09:26:11 +02:00
String header = imessage.getHeader("X-FairEmail-ID", null);
if (header == null)
header = imessage.getHeader("Message-ID", null);
return (header == null ? null : MimeUtility.unfold(header));
2018-08-02 13:33:06 +00:00
}
String[] getReferences() throws MessagingException {
2018-08-08 06:55:47 +00:00
String refs = imessage.getHeader("References", null);
2019-05-03 09:26:11 +02:00
return (refs == null ? new String[0] : MimeUtility.unfold(refs).split("\\s+"));
2018-08-02 13:33:06 +00:00
}
2018-09-18 08:55:59 +00:00
String getDeliveredTo() throws MessagingException {
2019-04-27 16:05:28 +02:00
String header = imessage.getHeader("Delivered-To", null);
if (header == null)
header = imessage.getHeader("X-Delivered-To", null);
2019-05-03 09:26:11 +02:00
return (header == null ? null : MimeUtility.unfold(header));
2018-09-18 08:55:59 +00:00
}
2018-08-02 13:33:06 +00:00
String getInReplyTo() throws MessagingException {
2019-05-03 09:26:11 +02:00
String header = imessage.getHeader("In-Reply-To", null);
return (header == null ? null : MimeUtility.unfold(header));
2018-08-02 13:33:06 +00:00
}
2019-03-30 10:57:29 +00:00
String getThreadId(Context context, long account, long uid) throws MessagingException {
List<String> refs = new ArrayList<>();
2018-08-02 13:33:06 +00:00
for (String ref : getReferences())
if (!TextUtils.isEmpty(ref))
2019-03-30 10:57:29 +00:00
refs.add(ref);
String inreplyto = getInReplyTo();
2019-03-30 10:57:29 +00:00
if (!TextUtils.isEmpty(inreplyto) && !refs.contains(inreplyto))
refs.add(inreplyto);
DB db = DB.getInstance(context);
for (String ref : refs) {
List<EntityMessage> messages = db.message().getMessageByMsgId(account, ref);
if (messages.size() > 0)
return messages.get(0).thread;
}
if (refs.size() > 0)
return refs.get(0);
2018-08-02 13:33:06 +00:00
String msgid = getMessageID();
return (TextUtils.isEmpty(msgid) ? Long.toString(uid) : msgid);
}
boolean getReceiptRequested() throws MessagingException {
return (imessage.getHeader("Return-Receipt-To") != null ||
imessage.getHeader("Disposition-Notification-To") != null);
}
2019-04-18 19:13:38 +02:00
Address[] getReceiptTo() throws MessagingException {
2019-06-22 13:26:45 +02:00
return getAddressHeader("Disposition-Notification-To");
2019-04-18 19:13:38 +02:00
}
String getAuthentication() throws MessagingException {
2019-05-03 09:26:11 +02:00
String header = imessage.getHeader("Authentication-Results", null);
return (header == null ? null : MimeUtility.unfold(header));
}
2019-04-12 20:41:06 +02:00
static Boolean getAuthentication(String type, String header) {
if (header == null)
return null;
// https://tools.ietf.org/html/rfc7601
Boolean result = null;
String[] part = header.split(";");
for (int i = 1; i < part.length; i++) {
String[] kv = part[i].split("=");
if (kv.length > 1) {
String key = kv[0].trim();
String[] val = kv[1].trim().split(" ");
if (val.length > 0 && type.equals(key)) {
if ("fail".equals(val[0]))
result = false;
else if ("pass".equals(val[0]))
if (result == null)
result = true;
}
}
}
return result;
}
2019-06-22 13:26:45 +02:00
private Address[] getAddressHeader(String name) throws MessagingException {
String header = imessage.getHeader(name, ",");
if (header == null)
return null;
header = new String(header.getBytes(StandardCharsets.ISO_8859_1));
return InternetAddress.parseHeader(header, false);
}
Address[] getFrom() throws MessagingException {
2019-06-22 13:26:45 +02:00
Address[] address = getAddressHeader("From");
if (address == null)
address = getAddressHeader("Sender");
return address;
2018-08-02 13:33:06 +00:00
}
Address[] getTo() throws MessagingException {
2019-06-22 13:26:45 +02:00
return getAddressHeader("To");
2018-08-02 13:33:06 +00:00
}
Address[] getCc() throws MessagingException {
2019-06-22 13:26:45 +02:00
return getAddressHeader("Cc");
2018-08-02 13:33:06 +00:00
}
Address[] getBcc() throws MessagingException {
2019-06-22 13:26:45 +02:00
return getAddressHeader("Bcc");
2018-08-03 07:39:43 +00:00
}
Address[] getReply() throws MessagingException {
2019-06-22 13:26:45 +02:00
return getAddressHeader("Reply-To");
2018-08-02 13:33:06 +00:00
}
2019-04-23 11:47:56 +02:00
Address[] getListPost() throws MessagingException {
2019-06-22 13:26:45 +02:00
String list;
2019-05-10 12:10:23 +02:00
try {
// https://www.ietf.org/rfc/rfc2369.txt
2019-06-09 13:21:56 +02:00
list = imessage.getHeader("List-Post", null);
2019-05-21 14:50:10 +02:00
if (list == null)
2019-05-10 12:10:23 +02:00
return null;
list = MimeUtility.unfold(list);
2019-06-14 08:46:33 +02:00
// List-Post: NO (posting not allowed on this list)
if (list != null && list.startsWith("NO"))
2019-06-04 17:04:01 +02:00
return null;
2019-05-21 14:50:10 +02:00
// https://www.ietf.org/rfc/rfc2368.txt
2019-06-09 15:46:36 +02:00
for (String _to : list.split(",")) {
String to = _to.trim();
2019-06-21 08:52:06 +02:00
int lt = to.indexOf("<");
int gt = to.lastIndexOf(">");
if (lt >= 0 && gt > lt)
2019-06-09 15:46:36 +02:00
try {
2019-06-21 08:52:06 +02:00
MailTo mailto = MailTo.parse(to.substring(lt + 1, gt));
2019-06-09 15:46:36 +02:00
if (mailto.getTo() != null)
return new Address[]{new InternetAddress(mailto.getTo().split(",")[0])};
} catch (android.net.ParseException ex) {
Log.i(ex);
}
}
2019-05-10 12:10:23 +02:00
2019-06-09 15:46:36 +02:00
Log.w(new IllegalArgumentException("List-Post: " + list));
2019-05-21 14:50:10 +02:00
return null;
2019-04-23 11:47:56 +02:00
} catch (AddressException ex) {
Log.w(ex);
return null;
2019-05-10 12:10:23 +02:00
}
2019-04-23 11:47:56 +02:00
}
2019-04-06 20:42:05 +02:00
String getSubject() throws MessagingException {
2019-05-03 09:26:11 +02:00
String subject = imessage.getHeader("Subject", null);
if (subject == null)
return null;
subject = MimeUtility.unfold(subject);
2019-06-22 13:26:45 +02:00
subject = new String(subject.getBytes(StandardCharsets.ISO_8859_1));
2019-05-02 16:14:17 +02:00
2019-06-22 13:26:45 +02:00
if (subject.startsWith("=?"))
2019-05-03 09:29:15 +02:00
try {
subject = MimeUtility.decodeText(subject);
} catch (UnsupportedEncodingException ex) {
Log.w(ex);
}
2019-06-01 19:28:51 +02:00
2019-06-22 13:26:45 +02:00
subject = decodeMime(subject);
return subject;
2019-01-01 14:58:51 +01:00
}
2019-04-05 11:08:18 +02:00
Long getSize() throws MessagingException {
long size = imessage.getSize();
2019-03-30 08:40:07 +00:00
if (size == 0)
throw new MessagingException("Message empty");
return (size < 0 ? null : size);
}
2019-02-10 19:47:46 +00:00
long getReceived() throws MessagingException {
2019-06-26 20:42:52 +02:00
Date received = imessage.getReceivedDate();
return (received == null ? new Date() : received).getTime();
2019-02-10 19:47:46 +00:00
}
Long getSent() throws MessagingException {
Date date = imessage.getSentDate();
return (date == null ? null : date.getTime());
}
2019-01-25 09:37:43 +00:00
String getHeaders() throws MessagingException {
StringBuilder sb = new StringBuilder();
Enumeration<Header> headers = imessage.getAllHeaders();
while (headers.hasMoreElements()) {
Header header = headers.nextElement();
sb.append(header.getName()).append(": ").append(header.getValue()).append("\n");
}
return sb.toString();
}
2019-01-18 14:25:26 +00:00
static String formatAddresses(Address[] addresses) {
return formatAddresses(addresses, true, false);
}
static String formatAddressesShort(Address[] addresses) {
return formatAddresses(addresses, false, false);
}
static String formatAddressesCompose(Address[] addresses) {
String result = formatAddresses(addresses, true, true);
if (!TextUtils.isEmpty(result))
result += ", ";
return result;
}
2019-01-20 10:18:42 +00:00
static String formatAddresses(Address[] addresses, boolean full, boolean compose) {
2018-08-28 14:59:52 +00:00
if (addresses == null || addresses.length == 0)
return "";
2018-08-02 13:33:06 +00:00
List<String> formatted = new ArrayList<>();
for (Address address : addresses)
if (address instanceof InternetAddress) {
InternetAddress a = (InternetAddress) address;
String personal = a.getPersonal();
if (TextUtils.isEmpty(personal))
2019-04-06 20:42:05 +02:00
formatted.add(a.getAddress());
2018-09-05 07:39:05 +00:00
else {
2019-01-18 14:25:26 +00:00
if (compose) {
boolean quote = false;
for (int i = 0; i < personal.length(); i++)
if ("()<>,;:\\\"[]@".indexOf(personal.charAt(i)) >= 0) {
quote = true;
break;
}
if (quote)
personal = "\"" + personal + "\"";
}
2018-09-05 07:39:05 +00:00
if (full)
formatted.add(personal + " <" + a.getAddress() + ">");
else
formatted.add(personal);
}
} else
formatted.add(address.toString());
2018-08-08 06:55:47 +00:00
return TextUtils.join(", ", formatted);
2018-08-02 13:33:06 +00:00
}
2019-05-12 18:22:41 +02:00
static String canonicalAddress(String address) {
String[] a = address.split("@");
if (a.length > 0) {
String[] extra = a[0].split("\\+");
if (extra.length > 0)
a[0] = extra[0];
}
return TextUtils.join("@", a).toLowerCase();
}
2019-04-26 10:14:07 +02:00
static String decodeMime(String text) {
2019-04-06 20:42:05 +02:00
if (text == null)
return null;
2019-06-24 09:59:44 +02:00
// https://tools.ietf.org/html/rfc2047
// encoded-word = "=?" charset "?" encoding "?" encoded-text "?="
2019-04-06 20:42:05 +02:00
int i = 0;
2019-05-13 20:26:37 +02:00
while (i < text.length()) {
int s = text.indexOf("=?", i);
if (s < 0)
break;
2019-06-24 09:59:44 +02:00
int q1 = text.indexOf("?", s + 2);
if (q1 < 0)
break;
int q2 = text.indexOf("?", q1 + 1);
if (q2 < 0)
break;
int e = text.indexOf("?=", q2 + 1);
2019-05-13 20:26:37 +02:00
if (e < 0)
break;
2019-04-06 20:42:05 +02:00
String decode = text.substring(s, e + 2);
try {
2019-04-26 13:31:20 +02:00
String decoded = MimeUtility.decodeWord(decode);
2019-04-26 10:14:07 +02:00
text = text.substring(0, s) + decoded + text.substring(e + 2);
2019-04-06 20:42:05 +02:00
i += decoded.length();
2019-04-26 13:31:20 +02:00
} catch (ParseException ex) {
2019-06-23 16:25:31 +02:00
Log.w(new IllegalArgumentException(text, ex));
2019-04-26 13:31:20 +02:00
i += decode.length();
2019-04-06 20:42:05 +02:00
} catch (UnsupportedEncodingException ex) {
2019-06-23 16:25:31 +02:00
Log.w(new IllegalArgumentException(text, ex));
2019-04-06 20:42:05 +02:00
i += decode.length();
}
}
2019-04-26 13:31:20 +02:00
2019-04-06 20:42:05 +02:00
return text;
}
2018-12-27 11:32:20 +00:00
static String getSortKey(Address[] addresses) {
if (addresses == null || addresses.length == 0)
return null;
InternetAddress address = (InternetAddress) addresses[0];
2018-12-28 08:04:56 +00:00
// Sort on name will result in inconsistent results
// because the sender name and sender contact name can differ
return address.getAddress();
2018-12-27 11:32:20 +00:00
}
2019-01-16 10:57:57 +00:00
class MessageParts {
private Part plain = null;
private Part html = null;
private List<AttachmentPart> attachments = new ArrayList<>();
2019-01-19 19:08:01 +00:00
private ArrayList<String> warnings = new ArrayList<>();
2018-08-03 12:07:51 +00:00
2019-05-04 20:52:21 +02:00
Boolean isPlainOnly() {
if (plain == null && html == null)
return null;
return (html == null);
}
String getHtml(Context context) throws MessagingException, IOException {
2019-01-17 08:09:33 +00:00
if (plain == null && html == null) {
2019-06-14 16:23:44 +02:00
Log.i("No body part");
2019-01-17 08:09:33 +00:00
warnings.add(context.getString(R.string.title_no_body));
2019-01-16 10:57:57 +00:00
return null;
2019-01-17 08:09:33 +00:00
}
2018-12-20 07:13:30 +01:00
2019-01-16 10:57:57 +00:00
String result;
Part part = (html == null ? plain : html);
2019-01-10 13:44:31 +00:00
2018-08-02 13:33:06 +00:00
try {
2018-12-20 07:13:30 +01:00
Object content = part.getContent();
2019-06-14 16:23:44 +02:00
Log.i("Content class=" + (content == null ? null : content.getClass().getName()));
if (content == null) {
warnings.add(context.getString(R.string.title_no_body));
return null;
}
2019-01-16 10:57:57 +00:00
if (content instanceof String)
result = (String) content;
else if (content instanceof InputStream)
// Typically com.sun.mail.util.QPDecoderStream
result = readStream((InputStream) content, "UTF-8");
else
result = content.toString();
} catch (IOException | FolderClosedException | MessageRemovedException ex) {
2019-04-25 16:11:32 +02:00
throw ex;
2019-01-16 10:57:57 +00:00
} catch (Throwable ex) {
2018-12-24 12:27:45 +00:00
Log.w(ex);
2019-06-26 16:51:29 +02:00
warnings.add(Helper.formatThrowable(ex, false));
2019-05-10 22:14:24 +02:00
return null;
2018-08-02 13:33:06 +00:00
}
2019-05-10 22:14:24 +02:00
try {
ContentType ct = new ContentType(part.getContentType());
String charset = ct.getParameter("charset");
if (TextUtils.isEmpty(charset)) {
if (BuildConfig.DEBUG)
warnings.add(context.getString(R.string.title_no_charset, ct.toString()));
// The first 127 characters are the same as in US-ASCII
result = new String(result.getBytes(StandardCharsets.ISO_8859_1));
2019-05-10 22:14:24 +02:00
} else {
2019-06-22 12:34:33 +02:00
if ("US-ASCII".equals(charset.toUpperCase()))
result = new String(result.getBytes(StandardCharsets.ISO_8859_1));
else {
if ("US-ASCII".equals(Charset.forName(charset).name()))
warnings.add(context.getString(R.string.title_no_charset, charset));
}
}
2019-05-10 22:14:24 +02:00
} catch (ParseException ex) {
Log.w(ex);
2019-06-26 16:51:29 +02:00
warnings.add(Helper.formatThrowable(ex, false));
2019-01-16 18:01:00 +00:00
}
result = result.replace("\0", "");
if (part.isMimeType("text/plain")) {
2019-05-09 15:59:51 +02:00
result = TextUtils.htmlEncode(result);
2019-05-09 09:25:16 +02:00
result = result.replaceAll("\\r?\\n", "<br />");
result = "<span>" + result + "</span>";
}
2018-12-20 07:13:30 +01:00
2019-01-17 08:11:41 +00:00
return result;
2018-08-29 05:31:00 +00:00
}
2019-02-06 16:40:47 +00:00
List<AttachmentPart> getAttachmentParts() {
2019-02-06 16:16:06 +00:00
return attachments;
}
List<EntityAttachment> getAttachments() {
2019-01-16 10:57:57 +00:00
List<EntityAttachment> result = new ArrayList<>();
for (AttachmentPart apart : attachments)
result.add(apart.attachment);
2019-01-16 10:57:57 +00:00
return result;
2018-08-02 13:33:06 +00:00
}
2019-06-26 21:21:09 +02:00
void downloadAttachment(Context context, EntityAttachment local) throws IOException, MessagingException {
List<EntityAttachment> remotes = getAttachments();
// Match attachment by attributes
// Some servers order attachments randomly
boolean found = false;
for (int i = 0; i < remotes.size(); i++) {
EntityAttachment remote = remotes.get(i);
if (Objects.equals(remote.name, local.name) &&
Objects.equals(remote.cid, local.cid)) {
found = true;
downloadAttachment(context, i, local);
}
}
if (!found) {
Log.w("Attachment not found local=" + local);
for (EntityAttachment remote : remotes)
Log.w("Attachment remote=" + remote);
throw new IllegalArgumentException("Attachment not found");
}
}
void downloadAttachment(Context context, int index, EntityAttachment local) throws MessagingException, IOException {
Log.i("downloading attachment id=" + local.id);
2018-08-02 13:33:06 +00:00
2019-03-14 07:18:42 +00:00
DB db = DB.getInstance(context);
2019-01-16 10:57:57 +00:00
// Get data
AttachmentPart apart = attachments.get(index);
2018-08-02 13:33:06 +00:00
2019-01-16 10:57:57 +00:00
// Download attachment
2019-06-26 21:21:09 +02:00
File file = EntityAttachment.getFile(context, local.id, local.name);
db.attachment().setProgress(local.id, null);
2019-02-22 16:59:23 +01:00
try (InputStream is = apart.part.getInputStream()) {
2019-01-16 10:57:57 +00:00
long size = 0;
2019-01-16 18:27:03 +00:00
long total = apart.part.getSize();
2019-06-07 12:19:13 +02:00
int lastprogress = 0;
2019-02-22 16:59:23 +01:00
try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) {
byte[] buffer = new byte[ATTACHMENT_BUFFER_SIZE];
for (int len = is.read(buffer); len != -1; len = is.read(buffer)) {
size += len;
os.write(buffer, 0, len);
// Update progress
2019-06-07 12:19:13 +02:00
if (total > 0) {
int progress = (int) (size * 100 / total / 20 * 20);
if (progress != lastprogress) {
lastprogress = progress;
2019-06-26 21:21:09 +02:00
db.attachment().setProgress(local.id, progress);
2019-06-07 12:19:13 +02:00
}
}
2019-02-22 16:59:23 +01:00
}
2019-01-05 14:09:47 +00:00
}
2019-01-16 10:57:57 +00:00
// Store attachment data
2019-06-26 21:21:09 +02:00
db.attachment().setDownloaded(local.id, size);
2019-01-16 10:57:57 +00:00
Log.i("Downloaded attachment size=" + size);
2019-04-25 20:40:37 +02:00
} catch (FolderClosedIOException ex) {
2019-06-26 21:21:09 +02:00
db.attachment().setError(local.id, Helper.formatThrowable(ex));
2019-04-25 20:40:37 +02:00
throw new FolderClosedException(ex.getFolder(), "downloadAttachment", ex);
2019-06-02 07:58:43 +02:00
} catch (MessageRemovedIOException ex) {
2019-06-26 21:21:09 +02:00
db.attachment().setError(local.id, Helper.formatThrowable(ex));
2019-06-02 07:58:43 +02:00
throw new MessagingException("downloadAttachment", ex);
2019-01-16 18:27:03 +00:00
} catch (Throwable ex) {
2019-01-16 10:57:57 +00:00
// Reset progress on failure
2019-06-26 21:21:09 +02:00
db.attachment().setError(local.id, Helper.formatThrowable(ex));
2019-03-14 08:05:28 +00:00
throw ex;
2019-01-16 10:57:57 +00:00
}
2018-08-03 12:07:51 +00:00
}
2019-01-16 18:01:00 +00:00
2019-01-19 19:08:01 +00:00
String getWarnings(String existing) {
if (existing != null)
warnings.add(0, existing);
2019-01-16 18:01:00 +00:00
if (warnings.size() == 0)
return null;
else
return TextUtils.join(", ", warnings);
}
2019-01-16 10:57:57 +00:00
}
2018-08-03 12:07:51 +00:00
2019-02-06 16:16:06 +00:00
class AttachmentPart {
2019-01-16 10:57:57 +00:00
String disposition;
String filename;
boolean pgp;
Part part;
EntityAttachment attachment;
2018-08-03 12:07:51 +00:00
}
MessageParts getMessageParts() throws IOException, FolderClosedException {
2019-01-16 10:57:57 +00:00
MessageParts parts = new MessageParts();
MimeMessage cmessage = imessage;
try {
// Load body structure
cmessage.getContentID();
} catch (MessagingException ex) {
// https://javaee.github.io/javamail/FAQ#imapserverbug
if ("Unable to load BODYSTRUCTURE".equals(ex.getMessage())) {
Log.w(ex);
2019-06-26 16:51:29 +02:00
parts.warnings.add(Helper.formatThrowable(ex, false));
try {
cmessage = new MimeMessage(imessage);
} catch (MessagingException ignored) {
}
}
}
getMessageParts(cmessage, parts, false);
2019-01-16 10:57:57 +00:00
return parts;
}
2018-09-06 10:24:30 +00:00
private void getMessageParts(Part part, MessageParts parts, boolean pgp) throws IOException, FolderClosedException {
2019-01-21 17:19:02 +00:00
try {
if (part.isMimeType("multipart/*")) {
2019-06-01 18:59:56 +02:00
Multipart multipart;
2019-06-02 09:16:21 +02:00
Object content = part.getContent();
2019-06-01 18:59:56 +02:00
if (content instanceof Multipart)
multipart = (Multipart) part.getContent();
2019-06-02 09:16:21 +02:00
else if (content instanceof String) {
2019-06-01 18:59:56 +02:00
String text = (String) content;
String sample = text.substring(0, Math.min(80, text.length()));
throw new ParseException(content.getClass().getName() + ": " + sample);
2019-06-02 09:16:21 +02:00
} else
throw new ParseException(content.getClass().getName());
2019-06-01 18:59:56 +02:00
2019-01-21 17:19:02 +00:00
for (int i = 0; i < multipart.getCount(); i++)
try {
Part cpart = multipart.getBodyPart(i);
getMessageParts(cpart, parts, pgp);
ContentType ct = new ContentType(cpart.getContentType());
if ("application/pgp-encrypted".equals(ct.getBaseType().toLowerCase()))
pgp = true;
} catch (ParseException ex) {
// Nested body: try to continue
// ParseException: In parameter list boundary="...">, expected parameter name, got ";"
Log.w(ex);
2019-06-26 16:51:29 +02:00
parts.warnings.add(Helper.formatThrowable(ex, false));
2019-01-21 17:19:02 +00:00
}
} else {
// https://www.iana.org/assignments/cont-disp/cont-disp.xhtml
String disposition;
2019-01-16 10:57:57 +00:00
try {
2019-01-21 17:19:02 +00:00
disposition = part.getDisposition();
2019-05-25 16:01:51 +02:00
if (disposition != null)
disposition = disposition.toLowerCase();
} catch (MessagingException ex) {
2019-01-16 10:57:57 +00:00
Log.w(ex);
2019-06-26 16:51:29 +02:00
parts.warnings.add(Helper.formatThrowable(ex, false));
2019-01-21 17:19:02 +00:00
disposition = null;
2019-01-16 10:57:57 +00:00
}
2018-08-22 15:13:01 +00:00
2019-01-21 17:19:02 +00:00
String filename;
try {
filename = part.getFileName();
} catch (MessagingException ex) {
Log.w(ex);
2019-06-26 16:51:29 +02:00
parts.warnings.add(Helper.formatThrowable(ex, false));
filename = null;
2019-01-21 17:19:02 +00:00
}
2018-08-22 15:13:01 +00:00
2019-01-21 17:19:02 +00:00
//Log.i("Part" +
// " disposition=" + disposition +
// " filename=" + filename +
// " content type=" + part.getContentType());
2019-01-16 10:57:57 +00:00
2019-01-21 17:19:02 +00:00
if (!Part.ATTACHMENT.equalsIgnoreCase(disposition) &&
((parts.plain == null && part.isMimeType("text/plain")) ||
(parts.html == null && part.isMimeType("text/html")))) {
if (part.isMimeType("text/plain"))
parts.plain = part;
else
parts.html = part;
} else {
AttachmentPart apart = new AttachmentPart();
apart.disposition = disposition;
apart.filename = filename;
apart.pgp = pgp;
apart.part = part;
ContentType ct;
try {
ct = new ContentType(apart.part.getContentType());
} catch (ParseException ex) {
Log.w(ex);
2019-06-26 16:51:29 +02:00
parts.warnings.add(Helper.formatThrowable(ex, false));
ct = new ContentType("application/octet-stream");
}
2019-05-11 07:52:30 +02:00
String[] cid = null;
try {
cid = apart.part.getHeader("Content-ID");
} catch (MessagingException ex) {
Log.w(ex);
2019-06-26 16:51:29 +02:00
parts.warnings.add(Helper.formatThrowable(ex, false));
2019-05-11 07:52:30 +02:00
}
apart.attachment = new EntityAttachment();
apart.attachment.name = apart.filename;
apart.attachment.type = ct.getBaseType().toLowerCase();
apart.attachment.disposition = apart.disposition;
apart.attachment.size = (long) apart.part.getSize();
apart.attachment.cid = (cid == null || cid.length == 0 ? null : MimeUtility.unfold(cid[0]));
apart.attachment.encryption = (apart.pgp ? EntityAttachment.PGP_MESSAGE : null);
if ("text/calendar".equalsIgnoreCase(apart.attachment.type) && TextUtils.isEmpty(apart.attachment.name))
apart.attachment.name = "invite.ics";
// Try to guess a better content type
// Sometimes PDF files are sent using the wrong type
if ("application/octet-stream".equalsIgnoreCase(apart.attachment.type)) {
String extension = Helper.getExtension(apart.attachment.name);
if (extension != null) {
String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase());
if (type != null) {
Log.w("Guessing file=" + apart.attachment.name + " type=" + type);
apart.attachment.type = type;
}
}
}
2019-05-25 16:01:51 +02:00
if (apart.attachment.size <= 0)
apart.attachment.size = null;
2019-05-24 09:19:22 +02:00
// https://tools.ietf.org/html/rfc2392
if (apart.attachment.cid != null) {
if (!apart.attachment.cid.startsWith("<"))
apart.attachment.cid = "<" + apart.attachment.cid;
if (!apart.attachment.cid.endsWith(">"))
apart.attachment.cid += ">";
}
2019-01-21 17:19:02 +00:00
parts.attachments.add(apart);
}
2019-01-05 14:09:47 +00:00
}
} catch (FolderClosedException ex) {
throw ex;
2019-01-21 17:19:02 +00:00
} catch (MessagingException ex) {
Log.w(ex);
2019-06-26 16:51:29 +02:00
parts.warnings.add(Helper.formatThrowable(ex, false));
2018-08-03 12:07:51 +00:00
}
2019-01-16 10:57:57 +00:00
}
2018-08-03 12:07:51 +00:00
2019-01-16 10:57:57 +00:00
private static String readStream(InputStream is, String charset) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
for (int len = is.read(buffer); len != -1; len = is.read(buffer))
os.write(buffer, 0, len);
return new String(os.toByteArray(), charset);
2018-08-02 13:33:06 +00:00
}
2018-12-25 08:22:07 +00:00
static boolean equal(Address[] a1, Address[] a2) {
if (a1 == null && a2 == null)
return true;
if (a1 == null || a2 == null)
return false;
if (a1.length != a2.length)
return false;
for (int i = 0; i < a1.length; i++)
if (!a1[i].toString().equals(a2[i].toString()))
return false;
return true;
2018-08-02 13:33:06 +00:00
}
}