-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCSmtp.cpp
2441 lines (2197 loc) · 74.8 KB
/
CSmtp.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
////////////////////////////////////////////////////////////////////////////////
// Original class CFastSmtp written by
// christopher w. backen <[email protected]>
// More details at: http://www.codeproject.com/KB/IP/zsmtp.aspx
//
// Modifications introduced by Jakub Piwowarczyk:
// 1. name of the class and functions
// 2. new functions added: SendData,ReceiveData and more
// 3. authentication added
// 4. attachments added
// 5 .comments added
// 6. DELAY_IN_MS removed (no delay during sending the message)
// 7. non-blocking mode
// More details at: http://www.codeproject.com/KB/mcpp/CSmtp.aspx
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// SSL/TLS support added by John Tang by making use of OpenSSL: http://www.openssl.org/
// More details at: http://www.codeproject.com/KB/IP/smtp_ssl.aspx
//
// PLAIN, CRAM-MD5 and DIGESTMD5 authentication added by David Johns
//
// Revision History:
// - Version 2.4: Updated with fixes reported as of 22 Oct 2015
// > Fixed issues with files being left opened and buffer not being deleted if an error occurs as discussed here: http://www.codeproject.com/Messages/4651730/Re-File-attachment.aspx
// - Thanks to Josep Sol?
// > Fixed issue with opening attachments as discussed here: http://www.codeproject.com/Messages/4640325/File-path-mistakenly-ommitted-from-file-name-when-.aspx
// - Thanks to Graham
// > Fixed potential memory leak as discussed here: http://www.codeproject.com/Messages/5010012/Memory-leaks.aspx
// - Thanks to LahPo
// > Made total message size limit larger as recommended here: http://stackoverflow.com/questions/22426686/csmtp-wont-send-an-e-mail-attachment-but-without-the-attachment-it-works-fine/28333737#28333737
// - Thanks to Stanislav
// > Fixed an issue with incomplete attachment file paths as discussed here: http://www.codeproject.com/Messages/5127588/Re-Attachment-does-not-come.aspx
// - Thanks to Member 11508846 and Member 11887128
// - Version 2.3: Updated with fixes reported as of 17 Aug 2013
// > Removed Bcc header so that recipients don't see who it was Bcc'd to as discussed here: http://www.codeproject.com/Messages/4633562/Bcc-and-mail-header.aspx
// - Thanks to o15s19
// > Fixed problem with attaching files that have unicode or reserved character filenames as discussed here: http://www.codeproject.com/Messages/4610174/Re-About-snprintf-FileName-255-Attachments-FileId-.aspx
// - Thanks to uni_gauldoth
// > Improved the method used for checking attachment file sizes as discussed here: http://www.codeproject.com/Messages/4562481/retreiving-file-size-for-attachments.aspx
// - Thanks to GKarRacer
// > Added #include <unistd.h> for linux compiles, which was required for gethostname as discussed here: http://www.codeproject.com/Messages/4551908/Works-on-Linux-CSmtp-cpp-needed-sharpinclude-unist.aspx
// - Thanks to jim fred
// - Version 2.2: Updated with fixes reported as of 6 May 2013
// > Fixed check on MsgBody.size() as discussed here: http://www.codeproject.com/Messages/4555663/Incorrect-range-check.aspx
// - Thanks to GKarRacer
// > Moved memory allocation and checking if attachments could be opened to before the MAIL command is
// issued to avoid throwing errors in a place where you can't terminate the connection gracefully without
// the email being sent corrupted
// > Changed all sprintf calls to snprintf to add greater security. #define'd snprintf to sprintf_s for
// MSVC. Also changed all strcpy to snprintf since that is the only way to use a secure function that
// is portable between standard C and MSVC since MS re-ordered the arguments between strcpy and
// strcpy_s
// > Fixed issue with SayQuit that could lead to infinite loop discussed here: http://www.codeproject.com/Messages/4451901/exception-in-SayQuit-could-lead-to-infinite-loop.aspx
// - Thanks to jcyangzh!
// > Fixed issue with AUTH PLAIN implementation discussed here: http://www.codeproject.com/Messages/4433069/looks-like-a-bug-in-plain-auth.aspx
// - Thanks to sbrytskyy!
// - Version 2.1: Updated with fixes reported as of 26 Mar 2012
// > Fixed issue in main.cpp with referring to USE_TLS in the wrong scope discussed here: http://www.codeproject.com/Messages/4151405/Re-USE_SSL-no-member-of-CSmtp.aspx
// - Thanks to Alan P Brown!
// > Added modifications to allow it to compile in Debian Linux discussed here: http://www.codeproject.com/Messages/4132697/linux-port-patch.aspx
// - Thanks to Oleg Dolgov!
// > Added ability to change the character set, inspired by this post: http://www.codeproject.com/Messages/4238701/Re-The-subject-contains-the-Chinese-letters-could-.aspx
// - Thanks to LeonHuang0726 and John TWC for the suggestion!
// > Added ability to request a read receipt by calling SetReadReceipt as proposed here: http://www.codeproject.com/Messages/3938944/Disposition-Notification-To.aspx
// - Thanks to Gospa for the suggestion!
// > Added check for Linux when adding paths of attachments in the MIME header as suggested here: http://www.codeproject.com/Messages/4357144/portability-bug-w-attachment-name.aspx
// - Thanks to Spike!
// > Switched method of setting private std::string variables to use the = operator as suggested here: http://www.codeproject.com/Messages/4356937/portability-bugs-w-std-string-and-exceptions.aspx
// - Thanks to Spike!
// > Added SetLocalHostName function proposed here: http://www.codeproject.com/Messages/4092347/bug-fixes-GetLocalHostName-Send.aspx
// - Thanks to jerko!
// > Added the modifications to allow it to compile in Linux described here: http://www.codeproject.com/Messages/3878620/My-vote-of-5.aspx
// - Thanks to korisk!
// > Added the fix that corrects behavior when m_sNameFrom is empty described here: http://www.codeproject.com/Messages/4196071/Bug-Mail-sent-by-mail-domain-com.aspx
// - Thanks to agenua.grupoi68!
// - Version 2.0: Updated to all fixes reported as of 23 Jun 2011:
// > Added the m_bAuthenticate member variable to be able to disable authentication
// even though it may be supported by the server. It defaults to true so if it is
// not set the library will act as it would have before the addition.
// > Added the ability to pass the security type, m_type, the new m_Authenticate flag,
// the login and password into the ConnectRemoteServer function. If these new arguments
// are not included in the call the function will work as it did before.
// > Added the ability to pass the new m_Authenticate flag into the SetSMTPServer function.
// If not provided, the function will act as it would before the addition.
// > Added fix described here: http://www.codeproject.com/Messages/3681792/Bug-when-reading-answer.aspx
// - Thanks to Martin Kjallman!
// > Added fixes described here: http://www.codeproject.com/Messages/3707662/Mistakes.aspx
// - Thanks to Karpov Andrey!
// > Added fixes described here: http://www.codeproject.com/Messages/3587166/Re-Possible-Solution-To-Misc-EHLO-Errors.aspx
// - Thanks to Jakub Piwowarczyk!
// - Version 1.9: Started with Revion 6 in code project http://www.codeproject.com/script/Articles/ListVersions.aspx?aid=98355
////////////////////////////////////////////////////////////////////////////////
#include "CSmtp.h"
#include "base64.h"
#include "openssl/err.h"
#include <cassert>
#ifndef LINUX
//Add "openssl-0.9.8l\out32" to Additional Library Directories
#pragma comment(lib, "ssleay32.lib")
#pragma comment(lib, "libeay32.lib")
#endif
Command_Entry command_list[] =
{
{command_INIT, 0, 5*60, 220, ECSmtp::SERVER_NOT_RESPONDING},
{command_EHLO, 5*60, 5*60, 250, ECSmtp::COMMAND_EHLO},
{command_AUTHPLAIN, 5*60, 5*60, 235, ECSmtp::COMMAND_AUTH_PLAIN},
{command_AUTHLOGIN, 5*60, 5*60, 334, ECSmtp::COMMAND_AUTH_LOGIN},
{command_AUTHCRAMMD5, 5*60, 5*60, 334, ECSmtp::COMMAND_AUTH_CRAMMD5},
{command_AUTHDIGESTMD5, 5*60, 5*60, 334, ECSmtp::COMMAND_AUTH_DIGESTMD5},
{command_DIGESTMD5, 5*60, 5*60, 335, ECSmtp::COMMAND_DIGESTMD5},
{command_USER, 5*60, 5*60, 334, ECSmtp::UNDEF_XYZ_RESPONSE},
{command_PASSWORD, 5*60, 5*60, 235, ECSmtp::BAD_LOGIN_PASS},
{command_MAILFROM, 5*60, 5*60, 250, ECSmtp::COMMAND_MAIL_FROM},
{command_RCPTTO, 5*60, 5*60, 250, ECSmtp::COMMAND_RCPT_TO},
{command_DATA, 5*60, 2*60, 354, ECSmtp::COMMAND_DATA},
{command_DATABLOCK, 3*60, 0, 0, ECSmtp::COMMAND_DATABLOCK}, // Here the valid_reply_code is set to zero because there are no replies when sending data blocks
{command_DATAEND, 3*60, 10*60, 250, ECSmtp::MSG_BODY_ERROR},
{command_QUIT, 5*60, 5*60, 221, ECSmtp::COMMAND_QUIT},
{command_STARTTLS, 5*60, 5*60, 220, ECSmtp::COMMAND_EHLO_STARTTLS}
};
Command_Entry* FindCommandEntry(SMTP_COMMAND command)
{
Command_Entry* pEntry = NULL;
for(size_t i = 0; i < sizeof(command_list)/sizeof(command_list[0]); ++i)
{
if(command_list[i].command == command)
{
pEntry = &command_list[i];
break;
}
}
assert(pEntry != NULL);
return pEntry;
}
// A simple string match
bool IsKeywordSupported(const char* response, const char* keyword)
{
assert(response != NULL && keyword != NULL);
if(response == NULL || keyword == NULL)
return false;
int res_len = strlen(response);
int key_len = strlen(keyword);
if(res_len < key_len)
return false;
int pos = 0;
for(; pos < res_len - key_len + 1; ++pos)
{
if(_strnicmp(keyword, response+pos, key_len) == 0)
{
if(pos > 0 &&
(response[pos - 1] == '-' ||
response[pos - 1] == ' ' ||
response[pos - 1] == '='))
{
if(pos+key_len < res_len)
{
if(response[pos+key_len] == ' ' ||
response[pos+key_len] == '=')
{
return true;
}
else if(pos+key_len+1 < res_len)
{
if(response[pos+key_len] == '\r' &&
response[pos+key_len+1] == '\n')
{
return true;
}
}
}
}
}
}
return false;
}
unsigned char* CharToUnsignedChar(const char *strIn)
{
unsigned char *strOut;
unsigned long length,
i;
length = strlen(strIn);
strOut = new unsigned char[length+1];
if(!strOut) return NULL;
for(i=0; i<length; i++) strOut[i] = (unsigned char) strIn[i];
strOut[length]='\0';
return strOut;
}
////////////////////////////////////////////////////////////////////////////////
// NAME: CSmtp
// DESCRIPTION: Constructor of CSmtp class.
// ARGUMENTS: none
// USES GLOBAL: none
// MODIFIES GL: m_iXPriority, m_iSMTPSrvPort, RecvBuf, SendBuf
// RETURNS: none
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-08
////////////////////////////////////////////////////////////////////////////////
CSmtp::CSmtp()
{
hSocket = INVALID_SOCKET;
m_bConnected = false;
m_iXPriority = XPRIORITY_NORMAL;
m_iSMTPSrvPort = 0;
m_bAuthenticate = true;
#ifndef LINUX
// Initialize WinSock
WSADATA wsaData;
WORD wVer = MAKEWORD(2,2);
if (WSAStartup(wVer,&wsaData) != NO_ERROR)
throw ECSmtp(ECSmtp::WSA_STARTUP);
if (LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 2 )
{
WSACleanup();
throw ECSmtp(ECSmtp::WSA_VER);
}
#endif
char hostname[255];
if(gethostname((char *) &hostname, 255) == SOCKET_ERROR) throw ECSmtp(ECSmtp::WSA_HOSTNAME);
m_sLocalHostName = hostname;
if((RecvBuf = new char[BUFFER_SIZE]) == NULL)
throw ECSmtp(ECSmtp::LACK_OF_MEMORY);
if((SendBuf = new char[BUFFER_SIZE]) == NULL)
throw ECSmtp(ECSmtp::LACK_OF_MEMORY);
m_type = NO_SECURITY;
m_ctx = NULL;
m_ssl = NULL;
m_bHTML = false;
m_bReadReceipt = false;
m_sCharSet = "US-ASCII";
}
////////////////////////////////////////////////////////////////////////////////
// NAME: CSmtp
// DESCRIPTION: Destructor of CSmtp class.
// ARGUMENTS: none
// USES GLOBAL: RecvBuf, SendBuf
// MODIFIES GL: RecvBuf, SendBuf
// RETURNS: none
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-08
////////////////////////////////////////////////////////////////////////////////
CSmtp::~CSmtp()
{
if(m_bConnected) DisconnectRemoteServer();
if(SendBuf)
{
delete[] SendBuf;
SendBuf = NULL;
}
if(RecvBuf)
{
delete[] RecvBuf;
RecvBuf = NULL;
}
CleanupOpenSSL();
#ifndef LINUX
WSACleanup();
#endif
}
////////////////////////////////////////////////////////////////////////////////
// NAME: AddAttachment
// DESCRIPTION: New attachment is added.
// ARGUMENTS: const char *Path - name of attachment added
// USES GLOBAL: Attachments
// MODIFIES GL: Attachments
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
void CSmtp::AddAttachment(const char *Path)
{
assert(Path);
Attachments.insert(Attachments.end(), Path);
}
////////////////////////////////////////////////////////////////////////////////
// NAME: AddRecipient
// DESCRIPTION: New recipient data is added i.e.: email and name. .
// ARGUMENTS: const char *email - mail of the recipient
// const char *name - name of the recipient
// USES GLOBAL: Recipients
// MODIFIES GL: Recipients
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
void CSmtp::AddRecipient(const char *email, const char *name)
{
if(!email)
throw ECSmtp(ECSmtp::UNDEF_RECIPIENT_MAIL);
Recipient recipient;
recipient.Mail = email;
if(name!=NULL) recipient.Name = name;
else recipient.Name.empty();
Recipients.insert(Recipients.end(), recipient);
}
////////////////////////////////////////////////////////////////////////////////
// NAME: AddCCRecipient
// DESCRIPTION: New cc-recipient data is added i.e.: email and name. .
// ARGUMENTS: const char *email - mail of the cc-recipient
// const char *name - name of the ccc-recipient
// USES GLOBAL: CCRecipients
// MODIFIES GL: CCRecipients
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
void CSmtp::AddCCRecipient(const char *email, const char *name)
{
if(!email)
throw ECSmtp(ECSmtp::UNDEF_RECIPIENT_MAIL);
Recipient recipient;
recipient.Mail = email;
if(name!=NULL) recipient.Name = name;
else recipient.Name.empty();
CCRecipients.insert(CCRecipients.end(), recipient);
}
////////////////////////////////////////////////////////////////////////////////
// NAME: AddBCCRecipient
// DESCRIPTION: New bcc-recipient data is added i.e.: email and name. .
// ARGUMENTS: const char *email - mail of the bcc-recipient
// const char *name - name of the bccc-recipient
// USES GLOBAL: BCCRecipients
// MODIFIES GL: BCCRecipients
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
void CSmtp::AddBCCRecipient(const char *email, const char *name)
{
if(!email)
throw ECSmtp(ECSmtp::UNDEF_RECIPIENT_MAIL);
Recipient recipient;
recipient.Mail = email;
if(name!=NULL) recipient.Name = name;
else recipient.Name.empty();
BCCRecipients.insert(BCCRecipients.end(), recipient);
}
////////////////////////////////////////////////////////////////////////////////
// NAME: AddMsgLine
// DESCRIPTION: Adds new line in a message.
// ARGUMENTS: const char *Text - text of the new line
// USES GLOBAL: MsgBody
// MODIFIES GL: MsgBody
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
void CSmtp::AddMsgLine(const char* Text)
{
MsgBody.insert(MsgBody.end(), Text);
}
////////////////////////////////////////////////////////////////////////////////
// NAME: DelMsgLine
// DESCRIPTION: Deletes specified line in text message.. .
// ARGUMENTS: unsigned int Line - line to be delete
// USES GLOBAL: MsgBody
// MODIFIES GL: MsgBody
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
void CSmtp::DelMsgLine(unsigned int Line)
{
if(Line >= MsgBody.size())
throw ECSmtp(ECSmtp::OUT_OF_MSG_RANGE);
MsgBody.erase(MsgBody.begin()+Line);
}
////////////////////////////////////////////////////////////////////////////////
// NAME: DelRecipients
// DESCRIPTION: Deletes all recipients. .
// ARGUMENTS: void
// USES GLOBAL: Recipients
// MODIFIES GL: Recipients
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
void CSmtp::DelRecipients()
{
Recipients.clear();
}
////////////////////////////////////////////////////////////////////////////////
// NAME: DelBCCRecipients
// DESCRIPTION: Deletes all BCC recipients. .
// ARGUMENTS: void
// USES GLOBAL: BCCRecipients
// MODIFIES GL: BCCRecipients
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
void CSmtp::DelBCCRecipients()
{
BCCRecipients.clear();
}
////////////////////////////////////////////////////////////////////////////////
// NAME: DelCCRecipients
// DESCRIPTION: Deletes all CC recipients. .
// ARGUMENTS: void
// USES GLOBAL: CCRecipients
// MODIFIES GL: CCRecipients
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
void CSmtp::DelCCRecipients()
{
CCRecipients.clear();
}
////////////////////////////////////////////////////////////////////////////////
// NAME: DelMsgLines
// DESCRIPTION: Deletes message text.
// ARGUMENTS: void
// USES GLOBAL: MsgBody
// MODIFIES GL: MsgBody
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
void CSmtp::DelMsgLines()
{
MsgBody.clear();
}
////////////////////////////////////////////////////////////////////////////////
// NAME: DelAttachments
// DESCRIPTION: Deletes all recipients. .
// ARGUMENTS: void
// USES GLOBAL: Attchments
// MODIFIES GL: Attachments
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
void CSmtp::DelAttachments()
{
Attachments.clear();
}
////////////////////////////////////////////////////////////////////////////////
// NAME: ModMsgLine
// DESCRIPTION: Modifies a specific line of the message body
// ARGUMENTS: unsigned int Line - the line number to modify
// const char* Text - the new contents of the line
// USES GLOBAL: MsgBody
// MODIFIES GL: MsgBody
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-07-07
////////////////////////////////////////////////////////////////////////////////
void CSmtp::ModMsgLine(unsigned int Line,const char* Text)
{
if(Text)
{
if(Line >= MsgBody.size())
throw ECSmtp(ECSmtp::OUT_OF_MSG_RANGE);
MsgBody.at(Line) = std::string(Text);
}
}
////////////////////////////////////////////////////////////////////////////////
// NAME: ClearMessage
// DESCRIPTION: Clears the recipients and message body
// ARGUMENTS: none
// RETURNS: none
// AUTHOR: David Johns
// AUTHOR/DATE: DRJ 2013-05-20
////////////////////////////////////////////////////////////////////////////////
void CSmtp::ClearMessage()
{
DelRecipients();
DelBCCRecipients();
DelCCRecipients();
DelAttachments();
DelMsgLines();
}
////////////////////////////////////////////////////////////////////////////////
// NAME: Send
// DESCRIPTION: Sending the mail. .
// ARGUMENTS: none
// USES GLOBAL: m_sSMTPSrvName, m_iSMTPSrvPort, SendBuf, RecvBuf, m_sLogin,
// m_sPassword, m_sMailFrom, Recipients, CCRecipients,
// BCCRecipients, m_sMsgBody, Attachments,
// MODIFIES GL: SendBuf
// RETURNS: void
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
// JP 2010-07-08
////////////////////////////////////////////////////////////////////////////////
void CSmtp::Send()
{
unsigned int i,rcpt_count,res,FileId;
char *FileBuf = NULL;
FILE* hFile = NULL;
unsigned long int FileSize,TotalSize,MsgPart;
string FileName,EncodedFileName;
string::size_type pos;
// ***** CONNECTING TO SMTP SERVER *****
// connecting to remote host if not already connected:
if(hSocket==INVALID_SOCKET)
{
if(!ConnectRemoteServer(m_sSMTPSrvName.c_str(), m_iSMTPSrvPort, m_type, m_bAuthenticate))
throw ECSmtp(ECSmtp::WSA_INVALID_SOCKET);
}
try{
//Allocate memory
if((FileBuf = new char[55]) == NULL)
throw ECSmtp(ECSmtp::LACK_OF_MEMORY);
//Check that any attachments specified can be opened
TotalSize = 0;
for(FileId=0;FileId<Attachments.size();FileId++)
{
// opening the file:
hFile = fopen(Attachments[FileId].c_str(), "rb");
if(hFile == NULL)
throw ECSmtp(ECSmtp::FILE_NOT_EXIST);
// checking file size:
fseek(hFile, 0, SEEK_END);
FileSize = ftell(hFile);
TotalSize += FileSize;
// sending the file:
if(TotalSize/1024 > MSG_SIZE_IN_MB*1024)
throw ECSmtp(ECSmtp::MSG_TOO_BIG);
fclose(hFile);
hFile=NULL;
}
// ***** SENDING E-MAIL *****
// MAIL <SP> FROM:<reverse-path> <CRLF>
if(!m_sMailFrom.size())
throw ECSmtp(ECSmtp::UNDEF_MAIL_FROM);
Command_Entry* pEntry = FindCommandEntry(command_MAILFROM);
snprintf(SendBuf, BUFFER_SIZE, "MAIL FROM:<%s>\r\n", m_sMailFrom.c_str());
SendData(pEntry);
ReceiveResponse(pEntry);
// RCPT <SP> TO:<forward-path> <CRLF>
if(!(rcpt_count = Recipients.size()))
throw ECSmtp(ECSmtp::UNDEF_RECIPIENTS);
pEntry = FindCommandEntry(command_RCPTTO);
for(i=0;i<Recipients.size();i++)
{
snprintf(SendBuf, BUFFER_SIZE, "RCPT TO:<%s>\r\n", (Recipients.at(i).Mail).c_str());
SendData(pEntry);
ReceiveResponse(pEntry);
}
for(i=0;i<CCRecipients.size();i++)
{
snprintf(SendBuf, BUFFER_SIZE, "RCPT TO:<%s>\r\n", (CCRecipients.at(i).Mail).c_str());
SendData(pEntry);
ReceiveResponse(pEntry);
}
for(i=0;i<BCCRecipients.size();i++)
{
snprintf(SendBuf, BUFFER_SIZE, "RCPT TO:<%s>\r\n", (BCCRecipients.at(i).Mail).c_str());
SendData(pEntry);
ReceiveResponse(pEntry);
}
pEntry = FindCommandEntry(command_DATA);
// DATA <CRLF>
snprintf(SendBuf, BUFFER_SIZE, "DATA\r\n");
SendData(pEntry);
ReceiveResponse(pEntry);
pEntry = FindCommandEntry(command_DATABLOCK);
// send header(s)
FormatHeader(SendBuf);
SendData(pEntry);
// send text message
if(GetMsgLines())
{
for(i=0;i<GetMsgLines();i++)
{
snprintf(SendBuf, BUFFER_SIZE, "%s\r\n",GetMsgLineText(i));
SendData(pEntry);
}
}
else
{
snprintf(SendBuf, BUFFER_SIZE, "%s\r\n"," ");
SendData(pEntry);
}
// next goes attachments (if they are)
for(FileId=0;FileId<Attachments.size();FileId++)
{
#ifndef LINUX
pos = Attachments[FileId].find_last_of("\\");
#else
pos = Attachments[FileId].find_last_of("/");
#endif
if(pos == string::npos) FileName = Attachments[FileId];
else FileName = Attachments[FileId].substr(pos+1);
//RFC 2047 - Use UTF-8 charset,base64 encode.
EncodedFileName = "=?UTF-8?B?";
EncodedFileName += base64_encode((unsigned char *) FileName.c_str(), FileName.size());
EncodedFileName += "?=";
snprintf(SendBuf, BUFFER_SIZE, "--%s\r\n", BOUNDARY_TEXT);
strcat(SendBuf, "Content-Type: application/x-msdownload; name=\"");
strcat(SendBuf, EncodedFileName.c_str());
strcat(SendBuf, "\"\r\n");
strcat(SendBuf, "Content-Transfer-Encoding: base64\r\n");
strcat(SendBuf, "Content-Disposition: attachment; filename=\"");
strcat(SendBuf, EncodedFileName.c_str());
strcat(SendBuf, "\"\r\n");
strcat(SendBuf, "\r\n");
SendData(pEntry);
// opening the file:
hFile = fopen(Attachments[FileId].c_str(), "rb");
if(hFile == NULL)
throw ECSmtp(ECSmtp::FILE_NOT_EXIST);
// get file size:
fseek(hFile, 0, SEEK_END);
FileSize = ftell(hFile);
fseek (hFile,0,SEEK_SET);
MsgPart = 0;
for(i=0;i<FileSize/54+1;i++)
{
res = fread(FileBuf,sizeof(char),54,hFile);
MsgPart ? strcat(SendBuf,base64_encode(reinterpret_cast<const unsigned char*>(FileBuf),res).c_str())
: strcpy(SendBuf,base64_encode(reinterpret_cast<const unsigned char*>(FileBuf),res).c_str());
strcat(SendBuf,"\r\n");
MsgPart += res + 2;
if(MsgPart >= BUFFER_SIZE/2)
{ // sending part of the message
MsgPart = 0;
SendData(pEntry); // FileBuf, FileName, fclose(hFile);
}
}
if(MsgPart)
{
SendData(pEntry); // FileBuf, FileName, fclose(hFile);
}
fclose(hFile);
hFile=NULL;
}
delete[] FileBuf;
FileBuf=NULL;
// sending last message block (if there is one or more attachments)
if(Attachments.size())
{
snprintf(SendBuf, BUFFER_SIZE, "\r\n--%s--\r\n",BOUNDARY_TEXT);
SendData(pEntry);
}
pEntry = FindCommandEntry(command_DATAEND);
// <CRLF> . <CRLF>
snprintf(SendBuf, BUFFER_SIZE, "\r\n.\r\n");
SendData(pEntry);
ReceiveResponse(pEntry);
}
catch(const ECSmtp&)
{
if(hFile) fclose(hFile);
if(FileBuf) delete[] FileBuf;
DisconnectRemoteServer();
throw;
}
}
////////////////////////////////////////////////////////////////////////////////
// NAME: ConnectRemoteServer
// DESCRIPTION: Connecting to the service running on the remote server.
// ARGUMENTS: const char *server - service name
// const unsigned short port - service port
// USES GLOBAL: m_pcSMTPSrvName, m_iSMTPSrvPort, SendBuf, RecvBuf, m_pcLogin,
// m_pcPassword, m_pcMailFrom, Recipients, CCRecipients,
// BCCRecipients, m_pcMsgBody, Attachments,
// MODIFIES GL: m_oError
// RETURNS: socket of the remote service
// AUTHOR: Jakub Piwowarczyk
// AUTHOR/DATE: JP 2010-01-28
////////////////////////////////////////////////////////////////////////////////
bool CSmtp::ConnectRemoteServer(const char* szServer, const unsigned short nPort_/*=0*/,
SMTP_SECURITY_TYPE securityType/*=DO_NOT_SET*/,
bool authenticate/*=true*/, const char* login/*=NULL*/,
const char* password/*=NULL*/)
{
unsigned short nPort = 0;
LPSERVENT lpServEnt;
SOCKADDR_IN sockAddr;
unsigned long ul = 1;
fd_set fdwrite,fdexcept;
timeval timeout;
int res = 0;
try
{
timeout.tv_sec = TIME_IN_SEC;
timeout.tv_usec = 0;
hSocket = INVALID_SOCKET;
if((hSocket = socket(PF_INET, SOCK_STREAM,0)) == INVALID_SOCKET)
throw ECSmtp(ECSmtp::WSA_INVALID_SOCKET);
if(nPort_ != 0)
nPort = htons(nPort_);
else
{
lpServEnt = getservbyname("mail", 0);
if (lpServEnt == NULL)
nPort = htons(25);
else
nPort = lpServEnt->s_port;
}
sockAddr.sin_family = AF_INET;
sockAddr.sin_port = nPort;
if((sockAddr.sin_addr.s_addr = inet_addr(szServer)) == INADDR_NONE)
{
LPHOSTENT host;
host = gethostbyname(szServer);
if (host)
memcpy(&sockAddr.sin_addr,host->h_addr_list[0],host->h_length);
else
{
#ifdef LINUX
close(hSocket);
#else
closesocket(hSocket);
#endif
throw ECSmtp(ECSmtp::WSA_GETHOSTBY_NAME_ADDR);
}
}
// start non-blocking mode for socket:
#ifdef LINUX
if(ioctl(hSocket,FIONBIO, (unsigned long*)&ul) == SOCKET_ERROR)
#else
if(ioctlsocket(hSocket,FIONBIO, (unsigned long*)&ul) == SOCKET_ERROR)
#endif
{
#ifdef LINUX
close(hSocket);
#else
closesocket(hSocket);
#endif
throw ECSmtp(ECSmtp::WSA_IOCTLSOCKET);
}
if(connect(hSocket,(LPSOCKADDR)&sockAddr,sizeof(sockAddr)) == SOCKET_ERROR)
{
#ifdef LINUX
if(errno != EINPROGRESS)
#else
if(WSAGetLastError() != WSAEWOULDBLOCK)
#endif
{
#ifdef LINUX
close(hSocket);
#else
closesocket(hSocket);
#endif
throw ECSmtp(ECSmtp::WSA_CONNECT);
}
}
else
return true;
while(true)
{
FD_ZERO(&fdwrite);
FD_ZERO(&fdexcept);
FD_SET(hSocket,&fdwrite);
FD_SET(hSocket,&fdexcept);
if((res = select(hSocket+1,NULL,&fdwrite,&fdexcept,&timeout)) == SOCKET_ERROR)
{
#ifdef LINUX
close(hSocket);
#else
closesocket(hSocket);
#endif
throw ECSmtp(ECSmtp::WSA_SELECT);
}
if(!res)
{
#ifdef LINUX
close(hSocket);
#else
closesocket(hSocket);
#endif
throw ECSmtp(ECSmtp::SELECT_TIMEOUT);
}
if(res && FD_ISSET(hSocket,&fdwrite))
break;
if(res && FD_ISSET(hSocket,&fdexcept))
{
#ifdef LINUX
close(hSocket);
#else
closesocket(hSocket);
#endif
throw ECSmtp(ECSmtp::WSA_SELECT);
}
} // while
FD_CLR(hSocket,&fdwrite);
FD_CLR(hSocket,&fdexcept);
if(securityType!=DO_NOT_SET) SetSecurityType(securityType);
if(GetSecurityType() == USE_TLS || GetSecurityType() == USE_SSL)
{
InitOpenSSL();
if(GetSecurityType() == USE_SSL)
{
OpenSSLConnect();
}
}
Command_Entry* pEntry = FindCommandEntry(command_INIT);
ReceiveResponse(pEntry);
SayHello();
if(GetSecurityType() == USE_TLS)
{
StartTls();
SayHello();
}
if(authenticate && IsKeywordSupported(RecvBuf, "AUTH") == true)
{
if(login) SetLogin(login);
if(!m_sLogin.size())
throw ECSmtp(ECSmtp::UNDEF_LOGIN);
if(password) SetPassword(password);
if(!m_sPassword.size())
throw ECSmtp(ECSmtp::UNDEF_PASSWORD);
if(IsKeywordSupported(RecvBuf, "LOGIN") == true)
{
pEntry = FindCommandEntry(command_AUTHLOGIN);
snprintf(SendBuf, BUFFER_SIZE, "AUTH LOGIN\r\n");
SendData(pEntry);
ReceiveResponse(pEntry);
// send login:
std::string encoded_login = base64_encode(reinterpret_cast<const unsigned char*>(m_sLogin.c_str()),m_sLogin.size());
pEntry = FindCommandEntry(command_USER);
snprintf(SendBuf, BUFFER_SIZE, "%s\r\n",encoded_login.c_str());
SendData(pEntry);
ReceiveResponse(pEntry);
// send password:
std::string encoded_password = base64_encode(reinterpret_cast<const unsigned char*>(m_sPassword.c_str()),m_sPassword.size());
pEntry = FindCommandEntry(command_PASSWORD);
snprintf(SendBuf, BUFFER_SIZE, "%s\r\n",encoded_password.c_str());
SendData(pEntry);
ReceiveResponse(pEntry);
}
else if(IsKeywordSupported(RecvBuf, "PLAIN") == true)
{
pEntry = FindCommandEntry(command_AUTHPLAIN);
snprintf(SendBuf, BUFFER_SIZE, "%s^%s^%s", m_sLogin.c_str(), m_sLogin.c_str(), m_sPassword.c_str());
unsigned int length = strlen(SendBuf);
unsigned char *ustrLogin = CharToUnsignedChar(SendBuf);
for(unsigned int i=0; i<length; i++)
{
if(ustrLogin[i]==94) ustrLogin[i]=0;
}
std::string encoded_login = base64_encode(ustrLogin, length);
delete[] ustrLogin;
snprintf(SendBuf, BUFFER_SIZE, "AUTH PLAIN %s\r\n", encoded_login.c_str());
SendData(pEntry);
ReceiveResponse(pEntry);
}
else if(IsKeywordSupported(RecvBuf, "CRAM-MD5") == true)
{
pEntry = FindCommandEntry(command_AUTHCRAMMD5);
snprintf(SendBuf, BUFFER_SIZE, "AUTH CRAM-MD5\r\n");
SendData(pEntry);
ReceiveResponse(pEntry);
std::string encoded_challenge = RecvBuf;
encoded_challenge = encoded_challenge.substr(4);
std::string decoded_challenge = base64_decode(encoded_challenge);
/////////////////////////////////////////////////////////////////////
//test data from RFC 2195
//decoded_challenge = "<[email protected]>";
//m_sLogin = "tim";
//m_sPassword = "tanstaaftanstaaf";
//MD5 should produce b913a602c7eda7a495b4e6e7334d3890
//should encode as dGltIGI5MTNhNjAyYzdlZGE3YTQ5NWI0ZTZlNzMzNGQzODkw
/////////////////////////////////////////////////////////////////////
unsigned char *ustrChallenge = CharToUnsignedChar(decoded_challenge.c_str());
unsigned char *ustrPassword = CharToUnsignedChar(m_sPassword.c_str());
if(!ustrChallenge || !ustrPassword)
throw ECSmtp(ECSmtp::BAD_LOGIN_PASSWORD);
// if ustrPassword is longer than 64 bytes reset it to ustrPassword=MD5(ustrPassword)
int passwordLength=m_sPassword.size();
if(passwordLength > 64){
MD5 md5password;
md5password.update(ustrPassword, passwordLength);
md5password.finalize();
ustrPassword = md5password.raw_digest();
passwordLength = 16;
}
//Storing ustrPassword in pads
unsigned char ipad[65], opad[65];
memset(ipad, 0, 64);
memset(opad, 0, 64);
memcpy(ipad, ustrPassword, passwordLength);
memcpy(opad, ustrPassword, passwordLength);
// XOR ustrPassword with ipad and opad values
for(int i=0; i<64; i++){
ipad[i] ^= 0x36;
opad[i] ^= 0x5c;
}
//perform inner MD5
MD5 md5pass1;
md5pass1.update(ipad, 64);
md5pass1.update(ustrChallenge, decoded_challenge.size());
md5pass1.finalize();
unsigned char *ustrResult = md5pass1.raw_digest();