-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathemailmessage.cpp
1587 lines (1408 loc) · 54.8 KB
/
emailmessage.cpp
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2011 Intel Corporation.
* Copyright (C) 2013-2019 Jolla Ltd.
*
* This program is licensed under the terms and conditions of the
* Apache License, version 2.0. The full text of the Apache License is at
* http://www.apache.org/licenses/LICENSE-2.0
*/
#include <QFileInfo>
#include <qmailaccount.h>
#include <qmailstore.h>
#include "emailmessage.h"
#include "logging_p.h"
#include <qmailnamespace.h>
#include <qmailcrypto.h>
#include <qmaildisconnected.h>
#include <QTextDocument>
#include <QTemporaryFile>
#include <QStandardPaths>
#include <QDir>
#include <QUrl>
#include <QtConcurrent>
#include <QFuture>
#include <QFutureWatcher>
namespace {
const QString READ_RECEIPT_HEADER_ID("Disposition-Notification-To");
const QString READ_RECEIPT_REPORT_PARAM_ID("report-type");
const QString READ_RECEIPT_REPORT_PARAM_VALUE("disposition-notification");
struct PartFinder {
PartFinder(const QByteArray &type, const QByteArray &subType, const QMailMessagePart *&part) : type(type), subType(subType), partFound(part) {}
QByteArray type;
QByteArray subType;
const QMailMessagePart *&partFound;
bool operator()(const QMailMessagePart &part) {
if (part.contentType().matches(type, subType)) {
partFound = const_cast<QMailMessagePart*>(&part);
return false;
}
return true;
}
};
// Supported image types by webkit
const QStringList supportedImageTypes = (QStringList() << "jpeg" << "jpg" << "png" << "gif" << "bmp" << "ico" << "webp");
}
EmailMessage::EmailMessage(QObject *parent)
: QObject(parent)
, m_account(QMailAccountId())
, m_id(QMailMessageId())
, m_originalMessageId(QMailMessageId())
, m_idToRemove(QMailMessageId())
, m_newMessage(true)
, m_requestReadReceipt(false)
, m_downloadActionId(0)
, m_htmlBodyConstructed(false)
, m_calendarStatus(Unknown)
, m_autoVerifySignature(false)
, m_signatureStatus(NoDigitalSignature)
{
setPriority(NormalPriority);
}
EmailMessage::~EmailMessage()
{
}
// ############ Slots ###############
void EmailMessage::onMessagesDownloaded(const QMailMessageIdList &ids, bool success)
{
for (const QMailMessageId &id : ids) {
if (id == m_id) {
disconnect(EmailAgent::instance(), SIGNAL(messagesDownloaded(QMailMessageIdList,bool)),
this, SLOT(onMessagesDownloaded(QMailMessageIdList,bool)));
if (success) {
// Reload the message
m_msg = QMailMessage(m_id);
m_bodyText = EmailAgent::instance()->bodyPlainText(m_msg);
emitMessageReloadedSignals();
emit messageDownloaded();
} else {
emit messageDownloadFailed();
}
return;
}
}
}
void EmailMessage::onMessagePartDownloaded(const QMailMessageId &messageId, const QString &partLocation, bool success)
{
if (messageId == m_id) {
// Reload the message
m_msg = QMailMessage(m_id);
QMailMessagePartContainer *plainTextcontainer = m_msg.findPlainTextContainer();
// // Check if is the html text part first
if (QMailMessagePartContainer *container = m_msg.findHtmlContainer()) {
QMailMessagePart::Location location = static_cast<const QMailMessagePart *>(container)->location();
if (location.toString(true) == partLocation) {
disconnect(EmailAgent::instance(), SIGNAL(messagePartDownloaded(QMailMessageId,QString,bool)),
this, SLOT(onMessagePartDownloaded(QMailMessageId,QString,bool)));
if (success) {
emit htmlBodyChanged();
// If plain text body is not present we also refresh quotedBody here
if (!plainTextcontainer) {
emit quotedBodyChanged();
}
}
return;
}
}
// Check if is the plain text part
if (plainTextcontainer) {
QMailMessagePart::Location location = static_cast<const QMailMessagePart *>(plainTextcontainer)->location();
if (location.toString(true) == partLocation) {
m_bodyText = EmailAgent::instance()->bodyPlainText(m_msg);
disconnect(EmailAgent::instance(), SIGNAL(messagePartDownloaded(QMailMessageId,QString,bool)),
this, SLOT(onMessagePartDownloaded(QMailMessageId,QString,bool)));
if (success) {
emit bodyChanged();
emit quotedBodyChanged();
}
return;
}
}
// Check if is the calendar invitation part
if (const QMailMessagePart *calendarPart = getCalendarPart()) {
QMailMessagePart::Location location = calendarPart->location();
if (location.toString(true) == partLocation) {
disconnect(EmailAgent::instance(), SIGNAL(messagePartDownloaded(QMailMessageId,QString,bool)),
this, SLOT(onMessagePartDownloaded(QMailMessageId,QString,bool)));
if (success) {
m_calendarStatus = Downloaded;
saveTempCalendarInvitation(*calendarPart);
} else {
m_calendarStatus = Failed;
qCWarning(lcEmail) << Q_FUNC_INFO << "Failed to download calendar invitation part";
}
emit calendarInvitationStatusChanged();
return;
}
}
}
}
void EmailMessage::onInlinePartDownloaded(const QMailMessageId &messageId, const QString &partLocation, bool success)
{
if (messageId == m_id) {
if (success) {
// Reload the message and insert the image
m_msg = QMailMessage(m_id);
QMailMessagePart &part = m_msg.partAt(m_partsToDownload.value(partLocation));
insertInlineImage(part);
} else {
// remove the image placeholder if the content fails to download
QMailMessagePart &part = m_msg.partAt(m_partsToDownload.value(partLocation));
removeInlineImagePlaceholder(part);
}
emit htmlBodyChanged();
m_partsToDownload.remove(partLocation);
if (m_partsToDownload.isEmpty()) {
emit inlinePartsDownloaded();
disconnect(EmailAgent::instance(), SIGNAL(messagePartDownloaded(QMailMessageId,QString,bool)),
this, SLOT(onInlinePartDownloaded(QMailMessageId,QString,bool)));
}
}
}
void EmailMessage::onSendCompleted(bool success)
{
emit sendCompleted(success);
}
// ############# Invokable API ########################
void EmailMessage::cancelMessageDownload()
{
if (m_downloadActionId) {
EmailAgent::instance()->cancelAction(m_downloadActionId);
disconnect(this, SLOT(onMessagesDownloaded(QMailMessageIdList,bool)));
disconnect(this, SLOT(onMessagePartDownloaded(QMailMessageId,QString,bool)));
}
}
void EmailMessage::downloadMessage()
{
requestMessageDownload();
}
void EmailMessage::getCalendarInvitation()
{
// Reload the message, because downloaded attachments might change parts location
// and this info should be updated before attempt of retrieving of the calendar part.
m_msg = QMailMessage(m_id);
if (const QMailMessagePart *calendarPart = getCalendarPart()) {
if (calendarPart->contentAvailable()) {
saveTempCalendarInvitation(*calendarPart);
} else {
qCDebug(lcEmail) << "Calendar invitation content not available yet, downloading";
m_calendarStatus = Downloading;
emit calendarInvitationStatusChanged();
if (m_msg.multipartType() == QMailMessage::MultipartNone) {
requestMessageDownload();
} else {
requestMessagePartDownload(calendarPart);
}
}
} else {
m_calendarInvitationUrl = QString();
emit calendarInvitationUrlChanged();
qCWarning(lcEmail) << Q_FUNC_INFO << "The message does not contain a calendar invitation";
}
}
typedef QPair<QSharedPointer<QMailMessage>, QMailCryptoFwd::SignatureResult> ThreadedSignedMessage;
static ThreadedSignedMessage signatureHelper(QMailMessage *msg,
const QString &engine,
const QStringList &keys)
{
// Encapsulate msg pointer into a QSharedPointer to ensure
// that it will be deleted when not needed anymore.
return ThreadedSignedMessage(QSharedPointer<QMailMessage>(msg),
QMailCryptographicServiceFactory::sign(*msg, engine, keys));
}
void EmailMessage::loadFromFile(const QString &path)
{
cancelMessageDownload();
m_msg = QMailMessage::fromRfc2822File(path);
m_msg.setStatus(QMailMessage::ContentAvailable, true);
m_msg.setStatus(QMailMessage::Temporary, true);
if (contentType() == EmailMessage::HTML)
emit htmlBodyChanged();
else
setBody(m_msg.body().data());
emit dateChanged();
emit fromChanged();
emit subjectChanged();
emit toChanged();
emit priorityChanged();
emit storedMessageChanged();
}
void EmailMessage::send()
{
//setting header here to make sure that used email address in a header is the latest one set for email message
updateReadReceiptHeader();
// Check if we are about to send a existent draft message
// if so create a new message with the draft content
if (m_msg.id().isValid()) {
QMailMessage newMessage;
EmailMessage::Priority previousMessagePriority = this->priority();
// Record any message properties we should retain
newMessage.setResponseType(m_msg.responseType());
newMessage.setParentAccountId(m_account.id());
newMessage.setFrom(m_account.fromAddress());
if (!m_originalMessageId.isValid() && m_msg.inResponseTo().isValid()) {
m_originalMessageId = m_msg.inResponseTo();
if (newMessage.responseType() == QMailMessage::UnspecifiedResponse ||
newMessage.responseType() == QMailMessage::NoResponse) {
newMessage.setResponseType(QMailMessage::Reply);
}
}
// Copy all headers
for (const QMailMessageHeaderField &headerField : m_msg.headerFields()) {
newMessage.appendHeaderField(headerField);
}
m_msg = newMessage;
this->setPriority(previousMessagePriority);
m_idToRemove = m_id;
m_id = QMailMessageId();
}
buildMessage(&m_msg);
// We may delay sending after asynchronous actions
// have been done, otherwise, we send immediately.
if (!m_signingKeys.isEmpty() && !m_signingPlugin.isEmpty()) {
// Ensure that the CryptographicServiceFactory object
// is created in the main thread.
QMailCryptographicServiceFactory::instance();
// Execute signature in a thread, using a copy of the message.
QMailMessage *signedCopy = new QMailMessage(m_msg);
QFutureWatcher<ThreadedSignedMessage> *signingWatcher
= new QFutureWatcher<ThreadedSignedMessage>(this);
connect(signingWatcher,
&QFutureWatcher<ThreadedSignedMessage>::finished,
this,
[=] {
signingWatcher->deleteLater();
m_msg = *signingWatcher->result().first;
onSignCompleted(signingWatcher->result().second);
});
QFuture<ThreadedSignedMessage> future
= QtConcurrent::run(signatureHelper, signedCopy,
m_signingPlugin, m_signingKeys);
signingWatcher->setFuture(future);
} else {
sendBuiltMessage();
}
}
void EmailMessage::sendBuiltMessage()
{
bool stored = false;
// Message present only on the local device until we externalise or send it
m_msg.setStatus(QMailMessage::LocalOnly, true);
stored = QMailStore::instance()->addMessage(&m_msg);
EmailAgent *emailAgent = EmailAgent::instance();
if (stored) {
connect(emailAgent, SIGNAL(sendCompleted(bool)), this, SLOT(onSendCompleted(bool)));
emailAgent->sendMessage(m_msg.id());
if (m_idToRemove.isValid()) {
emailAgent->expungeMessages(QMailMessageIdList() << m_idToRemove);
m_idToRemove = QMailMessageId();
}
// Send messages are always new at this point
m_newMessage = false;
emitSignals();
} else {
qCWarning(lcEmail) << "Error: queuing message, stored:" << stored;
}
emit sendEnqueued(stored);
}
void EmailMessage::onSignCompleted(QMailCryptoFwd::SignatureResult result)
{
if (result != QMailCryptoFwd::SignatureValid) {
qCWarning(lcEmail) << "Error: cannot sign message, SignatureResult: " << result;
setSignatureStatus(EmailMessage::SignedInvalid);
emit sendEnqueued(false);
} else {
setSignatureStatus(EmailMessage::SignedValid);
sendBuiltMessage();
}
}
bool EmailMessage::sendReadReceipt(const QString &subjectPrefix, const QString &readReceiptBodyText)
{
if (!m_msg.id().isValid()) {
qCWarning(lcEmail) << "cannot send read receipt for invalid message";
return false;
}
if (!requestReadReceipt()) {
return false;
}
const QString &toEmailAddress = readReceiptRequestEmail();
if (toEmailAddress.isEmpty()) {
qCWarning(lcEmail) << "Read receipt requested for email with invalid header value:" << toEmailAddress;
return false;
}
QMailMessage outgoingMessage;
QMailAccount account(m_msg.parentAccountId());
const QString &ownEmail = account.fromAddress().address();
outgoingMessage.setMultipartType(QMailMessagePartContainerFwd::MultipartReport,
QList<QMailMessageHeaderField::ParameterType>()
<< QMailMessageHeaderField::ParameterType(READ_RECEIPT_REPORT_PARAM_ID.toUtf8(),
READ_RECEIPT_REPORT_PARAM_VALUE.toUtf8()));
QMailMessagePart body = QMailMessagePart::fromData(
readReceiptBodyText.toUtf8(),
QMailMessageContentDisposition(QMailMessageContentDisposition::None),
QMailMessageContentType("text/plain"),
QMailMessageBody::Base64);
body.removeHeaderField("Content-Disposition");
// creating report part
QMailMessagePart disposition = QMailMessagePart::fromData(QString(),
QMailMessageContentDisposition(QMailMessageContentDisposition::None),
QMailMessageContentType("message/disposition-notification"),
QMailMessageBodyFwd::NoEncoding);
disposition.removeHeaderField("Content-Disposition");
disposition.setHeaderField("Reporting-UA", "sailfishos.org; Email application");
disposition.setHeaderField("Original-Recipient", ownEmail);
disposition.setHeaderField("Final-Recipient", ownEmail);
disposition.setHeaderField("Original-Message-ID", m_msg.headerField("Message-ID").content());
disposition.setHeaderField("Disposition", "manual-action/MDN-sent-manually; displayed");
QMailMessagePart alternative = QMailMessagePart::fromData(QString(),
QMailMessageContentDisposition(QMailMessageContentDisposition::None),
QMailMessageContentType(),
QMailMessageBodyFwd::NoEncoding);
alternative.setMultipartType(QMailMessage::MultipartAlternative);
alternative.removeHeaderField("Content-Disposition");
alternative.appendPart(body);
alternative.appendPart(disposition);
outgoingMessage.appendPart(alternative);
outgoingMessage.setResponseType(QMailMessageMetaDataFwd::Reply);
outgoingMessage.setParentAccountId(m_msg.parentAccountId());
outgoingMessage.setFrom(account.fromAddress());
outgoingMessage.setTo(QMailAddress(toEmailAddress));
outgoingMessage.setSubject(m_msg.subject().prepend(subjectPrefix));
// set message basic attributes
outgoingMessage.setDate(QMailTimeStamp::currentDateTime());
outgoingMessage.setStatus(QMailMessage::Outgoing, true);
outgoingMessage.setStatus(QMailMessage::ContentAvailable, true);
outgoingMessage.setStatus(QMailMessage::PartialContentAvailable, true);
outgoingMessage.setStatus(QMailMessage::Read, true);
outgoingMessage.setStatus((QMailMessage::Outbox | QMailMessage::Draft), true);
outgoingMessage.setParentFolderId(QMailFolder::LocalStorageFolderId);
outgoingMessage.setMessageType(QMailMessage::Email);
outgoingMessage.setSize(m_msg.indicativeSize() * 1024);
// Message present only on the local device until we externalise or send it
outgoingMessage.setStatus(QMailMessage::LocalOnly, true);
if (QMailStore::instance()->addMessage(&outgoingMessage)) {
EmailAgent *emailAgent = EmailAgent::instance();
emailAgent->sendMessage(outgoingMessage.id());
emailAgent->expungeMessages(QMailMessageIdList() << outgoingMessage.id());
} else {
qCWarning(lcEmail) << "Failed to add read receipt email into mail storage";
return false;
}
return true;
}
void EmailMessage::saveDraft()
{
buildMessage(&m_msg);
QMailAccount account(m_msg.parentAccountId());
QMailFolderId draftFolderId = account.standardFolder(QMailFolder::DraftsFolder);
if (draftFolderId.isValid()) {
m_msg.setParentFolderId(draftFolderId);
} else {
//local storage set on buildMessage step
qCWarning(lcEmail) << "Drafts folder not found, saving to local storage!";
}
bool saved = false;
// Unset outgoing and outbox so it wont really send
// when we sync to the server Drafts folder
m_msg.setStatus(QMailMessage::Outgoing, false);
m_msg.setStatus(QMailMessage::Outbox, false);
m_msg.setStatus(QMailMessage::Draft, true);
// This message is present only on the local device until we externalise or send it
m_msg.setStatus(QMailMessage::LocalOnly, true);
//setting readReceipt here to make sure that used email address is the latest one set for email message
updateReadReceiptHeader();
if (!m_msg.id().isValid()) {
saved = QMailStore::instance()->addMessage(&m_msg);
} else {
saved = QMailStore::instance()->updateMessage(&m_msg);
m_newMessage = false;
}
// Sync to the server, so the message will be in the remote Drafts folder
if (saved) {
QMailDisconnected::flagMessage(m_msg.id(), QMailMessage::Draft, QMailMessage::Temporary,
"Flagging message as draft");
QMailDisconnected::moveToFolder(QMailMessageIdList() << m_msg.id(), m_msg.parentFolderId());
EmailAgent::instance()->exportUpdates(QMailAccountIdList() << m_msg.parentAccountId());
emitSignals();
} else {
qCWarning(lcEmail) << "Failed to save message!";
}
}
QStringList EmailMessage::attachments()
{
if (m_id.isValid()) {
if (!(m_msg.status() & QMailMessageMetaData::HasAttachments))
return QStringList();
m_attachments.clear();
for (const QMailMessagePart::Location &location : m_msg.findAttachmentLocations()) {
const QMailMessagePart &attachmentPart = m_msg.partAt(location);
m_attachments << attachmentPart.displayName();
}
}
return m_attachments;
}
int EmailMessage::accountId() const
{
return m_msg.parentAccountId().toULongLong();
}
// Email address of the account having the message
QString EmailMessage::accountAddress() const
{
QMailAccount account(m_msg.parentAccountId());
return account.fromAddress().address();
}
int EmailMessage::folderId() const
{
return m_msg.parentFolderId().toULongLong();
}
QStringList EmailMessage::bcc() const
{
return QMailAddress::toStringList(m_msg.bcc());
}
QString EmailMessage::body()
{
if (QMailMessagePartContainer *container = m_msg.findPlainTextContainer()) {
if (container->contentAvailable()) {
if (m_bodyText.length()) {
return m_bodyText;
} else {
return QStringLiteral(" ");
}
} else {
if (m_msg.multipartType() == QMailMessage::MultipartNone) {
requestMessageDownload();
} else {
requestMessagePartDownload(container);
}
return QString();
}
} else {
// Fallback to body text when message does not have container. E.g. when
// we're composing an email message.
return m_bodyText;
}
}
QString EmailMessage::calendarInvitationUrl()
{
return m_calendarInvitationUrl;
}
bool EmailMessage::hasCalendarInvitation() const
{
return (m_msg.status() & QMailMessageMetaData::CalendarInvitation) != 0;
}
EmailMessage::AttachedDataStatus EmailMessage::calendarInvitationStatus() const
{
return m_calendarStatus;
}
QString EmailMessage::calendarInvitationBody() const
{
const QMailMessagePart *calendarPart = getCalendarPart();
return (calendarPart && calendarPart->contentAvailable()) ?
calendarPart->body().data() : QString();
}
bool EmailMessage::calendarInvitationSupportsEmailResponses() const
{
if (!hasCalendarInvitation()) {
return false;
}
// Exchange ActiveSync: Checking Message Class
if (m_msg.customField("X-EAS-MESSAGE-CLASS").compare("IPM.Schedule.Meeting.Request") == 0) {
return true; // Exchange ActiveSync invitations support response by email
}
// Add other account types here when those support response by email
return false;
}
QStringList EmailMessage::cc() const
{
return QMailAddress::toStringList(m_msg.cc());
}
EmailMessage::ContentType EmailMessage::contentType() const
{
// Treat only "text/plain" and invalid message as Plain and others as HTML.
if (m_id.isValid() || m_msg.contentAvailable()) {
if (m_msg.findHtmlContainer()
|| (m_msg.multipartType() == QMailMessagePartContainer::MultipartNone
&& m_msg.contentDisposition().type() == QMailMessageContentDisposition::Inline
&& m_msg.contentType().matches("image")
&& supportedImageTypes.contains(m_msg.contentType().subType().toLower()))) {
return EmailMessage::HTML;
} else {
return EmailMessage::Plain;
}
}
return EmailMessage::HTML;
}
bool EmailMessage::autoVerifySignature() const
{
return m_autoVerifySignature;
}
EmailMessage::SignatureStatus EmailMessage::signatureStatus() const
{
return m_signatureStatus;
}
QDateTime EmailMessage::date() const
{
return m_msg.date().toLocalTime();
}
QString EmailMessage::from() const
{
return m_msg.from().toString();
}
QString EmailMessage::fromAddress() const
{
return m_msg.from().address();
}
QString EmailMessage::fromDisplayName() const
{
return m_msg.from().name();
}
QString EmailMessage::htmlBody()
{
if (m_htmlBodyConstructed) {
return m_htmlText;
} else {
// Fallback to plain message if no html body.
QMailMessagePartContainer *container = m_msg.findHtmlContainer();
if (contentType() == EmailMessage::HTML && container) {
if (container->contentAvailable()) {
// Some email clients don't add html tags to the html
// body in case there's no content in the email body itself
if (container->body().data().length()) {
m_htmlText = container->body().data();
// Check if we have some inline parts
QList<QMailMessagePart::Location> inlineParts = m_msg.findInlinePartLocations();
if (!inlineParts.isEmpty()) {
// Check if we have something downloading already
if (m_partsToDownload.isEmpty()) {
insertInlineImages(inlineParts);
}
}
} else {
m_htmlText = QStringLiteral("<br/>");
}
m_htmlBodyConstructed = true;
return m_htmlText;
} else {
if (m_msg.multipartType() == QMailMessage::MultipartNone) {
requestMessageDownload();
} else {
requestMessagePartDownload(container);
}
return QString();
}
} else if (contentType() == EmailMessage::HTML) {
// Case with an in-line image.
// Create a fake HTML body to display the content inline.
if (m_msg.contentAvailable()) {
QString bodyData;
if (m_msg.body().transferEncoding() == QMailMessageBody::Base64) {
bodyData = QString::fromLatin1(m_msg.body().data(QMailMessageBody::Encoded));
} else {
bodyData = QString::fromLatin1(m_msg.body().data(QMailMessageBody::Decoded).toBase64());
}
m_htmlText = QString::fromLocal8Bit("<html><body><img src=\"data:%1;base64,%2\" nemo-inline-image-loading=\"no\" /></body></html>").arg(m_msg.contentDisposition().filename(), bodyData);
m_htmlBodyConstructed = true;
return m_htmlText;
} else {
requestMessageDownload();
}
return QString();
} else {
return body();
}
}
}
QString EmailMessage::inReplyTo() const
{
return m_msg.inReplyTo();
}
QString EmailMessage::signingPlugin() const
{
return m_signingPlugin;
}
QStringList EmailMessage::signingKeys() const
{
return m_signingKeys;
}
int EmailMessage::messageId() const
{
return m_id.toULongLong();
}
bool EmailMessage::multipleRecipients() const
{
QStringList recipients = this->recipients();
if (!recipients.size()) {
return false;
} else if (recipients.size() > 1) {
return true;
} else if (!recipients.contains(this->accountAddress(), Qt::CaseInsensitive)
&& !recipients.contains(this->replyTo(), Qt::CaseInsensitive)) {
return true;
} else {
return false;
}
}
int EmailMessage::numberOfAttachments() const
{
if (!(m_msg.status() & QMailMessageMetaData::HasAttachments))
return 0;
const QList<QMailMessagePart::Location> &attachmentLocations = m_msg.findAttachmentLocations();
return attachmentLocations.count();
}
int EmailMessage::originalMessageId() const
{
return m_originalMessageId.toULongLong();
}
QString EmailMessage::preview() const
{
return m_msg.preview();
}
EmailMessage::Priority EmailMessage::priority() const
{
if (m_msg.status() & QMailMessage::HighPriority) {
return HighPriority;
} else if (m_msg.status() & QMailMessage::LowPriority) {
return LowPriority;
} else {
return NormalPriority;
}
}
QString EmailMessage::quotedBody()
{
QString qBody;
QMailMessagePartContainer *container = m_msg.findPlainTextContainer();
if (container) {
qBody = body();
} else {
// If plain text body is not available we extract the text from the html part
QTextDocument doc;
doc.setHtml(htmlBody());
qBody = doc.toPlainText();
}
qBody.prepend('\n');
qBody.replace('\n', "\n> ");
qBody.truncate(qBody.size() - 1); // remove the extra ">" put there by QString.replace
return qBody;
}
QStringList EmailMessage::recipients() const
{
QStringList recipients;
QList<QMailAddress> addresses = m_msg.recipients();
for (const QMailAddress &address : addresses) {
recipients << address.address();
}
return recipients;
}
QStringList EmailMessage::recipientsDisplayName() const
{
QStringList recipients;
QList<QMailAddress> addresses = m_msg.recipients();
for (const QMailAddress &address : addresses) {
if (address.name().isEmpty()) {
recipients << address.address();
} else {
recipients << address.name();
}
}
return recipients;
}
bool EmailMessage::read() const
{
return (m_msg.status() & QMailMessage::Read);
}
QString EmailMessage::replyTo() const
{
return m_msg.replyTo().address();
}
EmailMessage::ResponseType EmailMessage::responseType() const
{
switch (m_msg.responseType()) {
case QMailMessage::NoResponse:
return NoResponse;
case QMailMessage::Reply:
return Reply;
case QMailMessage::ReplyToAll:
return ReplyToAll;
case QMailMessage::Forward:
return Forward;
case QMailMessage::ForwardPart:
return ForwardPart;
case QMailMessage::Redirect:
return Redirect;
case QMailMessage::UnspecifiedResponse:
default:
return UnspecifiedResponse;
}
}
bool EmailMessage::requestReadReceipt() const
{
return m_requestReadReceipt;
}
void EmailMessage::setAttachments(const QStringList &uris)
{
// Signals are only emited when message is constructed
m_attachments = uris;
}
void EmailMessage::setBcc(const QStringList &bccList)
{
if (bccList.size() || bcc().size()) {
m_msg.setBcc(QMailAddress::fromStringList(bccList));
emit bccChanged();
emit multipleRecipientsChanged();
}
}
void EmailMessage::setBody(const QString &body)
{
if (m_bodyText != body) {
m_bodyText = body;
emit bodyChanged();
}
}
void EmailMessage::setCc(const QStringList &ccList)
{
if (ccList.size() || cc().size()) {
m_msg.setCc(QMailAddress::fromStringList(ccList));
emit ccChanged();
emit multipleRecipientsChanged();
}
}
void EmailMessage::setFrom(const QString &sender)
{
if (!sender.isEmpty()) {
QMailAccountIdList accountIds = QMailStore::instance()->queryAccounts(QMailAccountKey::messageType(QMailMessage::Email)
& QMailAccountKey::status(QMailAccount::Enabled)
, QMailAccountSortKey::name());
// look up the account id for the given sender
for (const QMailAccountId &id : accountIds) {
QMailAccount account(id);
QMailAddress from = account.fromAddress();
if (from.address() == sender || from.toString() == sender || from.name() == sender) {
m_account = account;
m_msg.setParentAccountId(id);
m_msg.setFrom(account.fromAddress());
}
}
emit fromChanged();
emit accountIdChanged();
emit accountAddressChanged();
} else {
qCWarning(lcEmail) << Q_FUNC_INFO << "Can't set a empty 'From' address.";
}
}
void EmailMessage::setInReplyTo(const QString &messageId)
{
if (!messageId.isEmpty()) {
m_msg.setInReplyTo(messageId);
emit inReplyToChanged();
} else {
qCWarning(lcEmail) << Q_FUNC_INFO << "Can't set a empty messageId as 'InReplyTo' header.";
}
}
void EmailMessage::setSigningPlugin(const QString &cryptoType)
{
if (cryptoType == m_signingPlugin)
return;
m_signingPlugin = cryptoType;
emit signingPluginChanged();
emit cryptoProtocolChanged();
}
void EmailMessage::setSigningKeys(const QStringList &fingerPrints)
{
if (fingerPrints == m_signingKeys)
return;
m_signingKeys = fingerPrints;
emit signingKeysChanged();
emit cryptoProtocolChanged();
}
void EmailMessage::setMessageId(int messageId)
{
QMailMessageId msgId(messageId);
if (msgId != m_id) {
if (msgId.isValid()) {
m_id = msgId;
m_msg = QMailMessage(msgId);
} else {
m_id = QMailMessageId();
m_msg = QMailMessage();
qCWarning(lcEmail) << "Invalid message id" << msgId.toULongLong();
}
// Construct initial plain text body, even if not entirely available.
m_bodyText = EmailAgent::instance()->bodyPlainText(m_msg);
m_htmlBodyConstructed = false;
m_partsToDownload.clear();
if (!m_msg.headerField(READ_RECEIPT_HEADER_ID).isNull() && !m_requestReadReceipt) {
// we have a header field in a message, but m_requestReadReceipt is false, so we need to update m_requestReadReceipt value.
m_requestReadReceipt = true;
} else if (m_msg.headerField(READ_RECEIPT_HEADER_ID).isNull() && m_requestReadReceipt) {
// we do not have a header field in a message, but m_requestReadReceipt is true, so we need to update m_requestReadReceipt value.
m_requestReadReceipt = false;
}
// Message loaded from the store (or a empty message), all properties changes
emitMessageReloadedSignals();
}
}
void EmailMessage::setOriginalMessageId(int messageId)
{
m_originalMessageId = QMailMessageId(messageId);
emit originalMessageIdChanged();
}
void EmailMessage::setPriority(EmailMessage::Priority priority)
{
switch (priority) {
case HighPriority:
m_msg.setHeaderField("X-Priority", "1");
m_msg.setHeaderField("Importance", "high");
m_msg.setStatus(QMailMessage::LowPriority, false);
m_msg.setStatus(QMailMessage::HighPriority, true);
break;
case LowPriority:
m_msg.setHeaderField("X-Priority", "5");
m_msg.setHeaderField("Importance", "low");
m_msg.setStatus(QMailMessage::HighPriority, false);
m_msg.setStatus(QMailMessage::LowPriority, true);
break;
case NormalPriority:
default:
m_msg.setHeaderField("X-Priority", "3");
m_msg.removeHeaderField("Importance");
m_msg.setStatus(QMailMessage::HighPriority, false);
m_msg.setStatus(QMailMessage::LowPriority, false);
break;
}
emit priorityChanged();
}
void EmailMessage::setRead(bool read) {
if (read != this->read()) {
if (read) {
EmailAgent::instance()->markMessageAsRead(m_id.toULongLong());
} else {
EmailAgent::instance()->markMessageAsUnread(m_id.toULongLong());
}
m_msg.setStatus(QMailMessage::Read, read);
emit readChanged();
}
}
void EmailMessage::setReplyTo(const QString &address)
{
if (!address.isEmpty()) {
QMailAddress addr(address);
m_msg.setReplyTo(addr);
emit replyToChanged();