本文转载于CSDN,找了好久才找到的可用的邮件代码!

1
2
3
原文标题:c++实现smtp发送邮件,支持ssl的465端口发送,支持附件、一次发送多人、抄送等
原文链接:https://blog.csdn.net/weixin_44979075/article/details/131094396
原文作者:樱花回忆

前言

c++实现smtp发送邮件,支持ssl的465端口发送,支持附件、一次发送多人、抄送等。

这里只使用了openssl库(用来支持ssl的465端口),其他部分是原生c++,支持在win/linux运行。

网上很多都是原始的支持25端口,明文发送,这里介绍一下ssl思路

实现思路

使用sockect编程和ssl,使用SMTP协议

使用了c++的多态语言特性,包括重载和虚函数。

文中给出mail.h 和mail.cpp 以及main.cpp部分测试代码
Linux安装openssl

1
sudo apt install libssl-dev

win下自行下载安装

SMTP协议简介

SMTP协议的定义

1、SMTP 是一种TCP协议支持的提供可靠且有效电子邮件传输的应用层协议;
2、SMTP 是建立在 TCP上的一种邮件服务,主要用于传输系统之间的邮件信息并提供来信有关的通知;
3、SMTP 独立于特定的传输子系统,且只需要可靠有序的数据流信道支持;
4、SMTP 重要特性之一是其能跨越网络传输邮件,即“ SMTP 邮件中继”;
5、SMTP是一个相对简单的基于文本的协议。

SMTP基本命令

SMTP基本命令包括以下几个:HELO﹑EHLO、MAIL﹑RCPT﹑DATA、AUTH LOGIN和QUIT
1、HELO–发件方问候收件方,后面是发件人的服务器地址或标识。收件方回答OK时标识自己的身份。问候和确认过程表明两台机器可以进行通信,同时状态参量被复位,缓冲区被清空。
EHLO–申明身份,表示自己身份需要验证,注意这部分需要通过Telnet验证一下,是user@example.com还是user,否则会出错。
2、MAIL–这个命令用来开始传送邮件,它的后面跟随发件方邮件地址(返回邮件地址)。它也用来当邮件无法送达时,发送失败通知。为保证邮件的成功发送,发件方的地址应是被对方或中间转发方同意接受的。这个命令会清空有关的缓冲区,为新的邮件做准备。
3、RCPT –这个命令告诉收件方收件人的邮箱。当有多个收件人时,需要多次使用该命令RCPT
4、TO,每次只能指明一个人。如果接收方服务器不同意转发这个地址的邮件,它必须报550错误代码通知发件方。如果服务器同意转发,它要更改邮件发送路径,把最开始的目的地(该服务器)换成下一个服务器。
5、DATA–收件方把该命令之后的数据作为发送的数据。数据被加入数据缓冲区中,以单独一行是”.”的行结束数据。结束行对于接收方同时意味立即开始缓冲区内的数据传送,传送结束后清空缓冲区。如果传送接受,接收方回复OK。
6、QUIT–SMTP要求接收放必须回答OK,然后中断传输;在收到这个命令并回答OK前,收件方不得中断连接,即使传输出现错误。发件方在发出这个命令并收到OK答复前,也不得中断连接。
7、AUTH LOGIN–登录邮箱,这一部分一般要用base64加密。

头文件mail.h

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
#pragma once
#include <string>
#include <vector>
#include <map>

#include <openssl/ossl_typ.h>

#ifndef WIN32
#include<netdb.h>
#endif

class SmtpBase
{
protected:
struct EmailInfo
{
std::string smtpServer; //the SMTP server
std::string serverPort; //the SMTP server port
std::string charset; //the email character set
std::string sender; //the sender's name
std::string senderEmail; //the sender's email
std::string password; //the password of sender
std::string recipient; //the recipient's name
std::string recipientEmail; //the recipient's email

std::map<std::string, std::string> recvList; //收件人列表<email, name>

std::string subject; //the email message's subject 邮件主题
std::string message; //the email message body 邮件内容

std::map<std::string, std::string> ccEmail; //抄送列表
std::vector<std::string> attachment; //附件
};
public:

virtual ~SmtpBase() {}
/**
* @brief 简单发送文本邮件
* @param from 发送者的帐号
* @param passs 发送者密码
* @param to 收件人
* @param subject 主题
* @param strMessage 邮件内容
*/

virtual int SendEmail(const std::string& from, const std::string& passs, const std::string& to, const std::string& subject, const std::string& strMessage) = 0;
/**
* @brief 发送邮件,包括附件以及抄送人和多个收件人
* @param from 发送者的帐号
* @param passs 发送者密码
* @param vecTo 收件人列表
* @param subject 主题
* @param strMessage 邮件内容
* @param attachment 附件列表 附件可以是绝对路径,默认是可执行程序目录下
* @param ccList 抄送列表
*/
virtual int SendEmail(const std::string& from, const std::string& passs, const std::vector<std::string>& vecTo,
const std::string& subject, const std::string& strMessage, const std::vector<std::string>& attachment,const std::vector<std::string>& ccList) = 0;

std::string GetLastError()
{
return m_lastErrorMsg;
}

virtual int Read(void* buf, int num) = 0;
virtual int Write(const void* buf, int num) = 0;
virtual int Connect() = 0;
virtual int DisConnect() = 0;

protected:

std::string m_lastErrorMsg;


};


class SmtpEmail : public SmtpBase
{

public:
SmtpEmail(const std::string& emailHost, const std::string& port);
~SmtpEmail();

int SendEmail(const std::string& from, const std::string& passs, const std::string& to, const std::string& subject, const std::string& strMessage);

int SendEmail(const std::string& from, const std::string& passs, const std::vector<std::string>& vecTo,
const std::string& subject, const std::string& strMessage, const std::vector<std::string>& attachment, const std::vector<std::string>& ccList);
protected:
int Read(void* buf, int num);
int Write(const void* buf, int num);
int Connect();
int DisConnect();

virtual std::string GetEmailBody(const EmailInfo & info);
private:
//int SMTPSSLComunicate(SSL *connection, const EmailInfo &info);
int SMTPComunicate(const EmailInfo &info);




protected:
addrinfo* m_addrinfo;
int m_socketfd;

std::string m_host;
std::string m_port;

bool m_isConnected;
};

class SimpleSmtpEmail : public SmtpEmail
{
public:
using SmtpEmail::SmtpEmail;
virtual std::string GetEmailBody(const EmailInfo & info);
};

class SslSmtpEmail : public SmtpEmail
{
public:
using SmtpEmail::SmtpEmail;
~SslSmtpEmail();

int Connect();
int DisConnect();
protected:
int Read(void* buf, int num);
int Write(const void* buf, int num);
private:
SSL_CTX *m_ctx;
SSL *m_ssl;
};

class SimpleSslSmtpEmail : public SslSmtpEmail
{
public:
using SslSmtpEmail::SslSmtpEmail;
virtual std::string GetEmailBody(const EmailInfo & info);
};

实现文件mail.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
#ifdef WIN32
#include <WinSock2.h>
#endif
#include "mail.h"
#include <fstream>
#include <sstream>
#include <iostream>
#include <string.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#ifdef WIN32
#include <WinSock2.h>
#include <WS2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
#else
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#define INVALID_SOCKET -1
#endif

template<typename T>
std::string join(T& vecData, const std::string& delim)
{
if (vecData.size() <= 0)
{
return std::string();
}
std::stringstream ss;
for (auto& item : vecData)
{
ss << delim << item ;
}

return ss.str().substr(delim.length());
}

const char MimeTypes[][2][128] =
{
{ "***", "application/octet-stream" },
{ "csv", "text/csv" },
{ "tsv", "text/tab-separated-values" },
{ "tab", "text/tab-separated-values" },
{ "html", "text/html" },
{ "htm", "text/html" },
{ "doc", "application/msword" },
{ "docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" },
{ "ods", "application/x-vnd.oasis.opendocument.spreadsheet" },
{ "odt", "application/vnd.oasis.opendocument.text" },
{ "rtf", "application/rtf" },
{ "sxw", "application/vnd.sun.xml.writer" },
{ "txt", "text/plain" },
{ "xls", "application/vnd.ms-excel" },
{ "xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" },
{ "pdf", "application/pdf" },
{ "ppt", "application/vnd.ms-powerpoint" },
{ "pps", "application/vnd.ms-powerpoint" },
{ "pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation" },
{ "wmf", "image/x-wmf" },
{ "atom", "application/atom+xml" },
{ "xml", "application/xml" },
{ "json", "application/json" },
{ "js", "application/javascript" },
{ "ogg", "application/ogg" },
{ "ps", "application/postscript" },
{ "woff", "application/x-woff" },
{ "xhtml","application/xhtml+xml" },
{ "xht", "application/xhtml+xml" },
{ "zip", "application/zip" },
{ "gz", "application/x-gzip" },
{ "rar", "application/rar" },
{ "rm", "application/vnd.rn-realmedia" },
{ "rmvb", "application/vnd.rn-realmedia-vbr" },
{ "swf", "application/x-shockwave-flash" },
{ "au", "audio/basic" },
{ "snd", "audio/basic" },
{ "mid", "audio/mid" },
{ "rmi", "audio/mid" },
{ "mp3", "audio/mpeg" },
{ "aif", "audio/x-aiff" },
{ "aifc", "audio/x-aiff" },
{ "aiff", "audio/x-aiff" },
{ "m3u", "audio/x-mpegurl" },
{ "ra", "audio/vnd.rn-realaudio" },
{ "ram", "audio/vnd.rn-realaudio" },
{ "wav", "audio/x-wave" },
{ "wma", "audio/x-ms-wma" },
{ "m4a", "audio/x-m4a" },
{ "bmp", "image/bmp" },
{ "gif", "image/gif" },
{ "jpe", "image/jpeg" },
{ "jpeg", "image/jpeg" },
{ "jpg", "image/jpeg" },
{ "jfif", "image/jpeg" },
{ "png", "image/png" },
{ "svg", "image/svg+xml" },
{ "tif", "image/tiff" },
{ "tiff", "image/tiff" },
{ "ico", "image/vnd.microsoft.icon" },
{ "css", "text/css" },
{ "bas", "text/plain" },
{ "c", "text/plain" },
{ "h", "text/plain" },
{ "rtx", "text/richtext" },
{ "mp2", "video/mpeg" },
{ "mpa", "video/mpeg" },
{ "mpe", "video/mpeg" },
{ "mpeg", "video/mpeg" },
{ "mpg", "video/mpeg" },
{ "mpv2", "video/mpeg" },
{ "mov", "video/quicktime" },
{ "qt", "video/quicktime" },
{ "lsf", "video/x-la-asf" },
{ "lsx", "video/x-la-asf" },
{ "asf", "video/x-ms-asf" },
{ "asr", "video/x-ms-asf" },
{ "asx", "video/x-ms-asf" },
{ "avi", "video/x-msvideo" },
{ "3gp", "video/3gpp" },
{ "3gpp", "video/3gpp" },
{ "3g2", "video/3gpp2" },
{ "movie","video/x-sgi-movie" },
{ "mp4", "video/mp4" },
{ "wmv", "video/x-ms-wmv" },
{ "webm","video/webm" },
{ "m4v", "video/x-m4v" },
{ "flv", "video/x-flv" }
};


std::string fileBasename(const std::string path)
{
std::string filename = path.substr(path.find_last_of("/\\") + 1);//解析出文件名字
return filename;
}

std::string getFileContents(const char *filename)
{
std::ifstream in(filename, std::ios::in | std::ios::binary);
if (in)
{
std::string contents;
in.seekg(0, std::ios::end);
contents.resize(in.tellg());
in.seekg(0, std::ios::beg);
in.read(&contents[0], contents.size());
in.close();
return(contents);
}
else {
printf("文件读取失败:%s\n",filename);
return "";
}
}
//获取文件的后缀名 如xxx.jpg 获取的是jpg
std::string GetFileExtension(const std::string& FileName)
{
if (FileName.find_last_of(".") != std::string::npos) //find_last_of逆向查找在原字符串中最后一个与指定字符串(或字符)中的某个字符匹配的字符,返回它的位置。若查找失败,则返回npos。
return FileName.substr(FileName.find_last_of(".") + 1);
return "";
}

const char* GetMimeTypeFromFileName(char* szFileExt)
{
for (unsigned int i = 0; i < sizeof(MimeTypes) / sizeof(MimeTypes[0]); i++)
{
if (strcmp(MimeTypes[i][0], szFileExt) == 0)
{
return MimeTypes[i][1];
}
}
return MimeTypes[0][1]; //if does not match any, "application/octet-stream" is returned
}

char* base64Encode(char const* origSigned, unsigned origLength)
{
static const char base64Char[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
unsigned char const* orig = (unsigned char const*)origSigned; // in case any input bytes have the MSB set
if (orig == NULL) return NULL;

unsigned const numOrig24BitValues = origLength / 3;
bool havePadding = origLength > numOrig24BitValues * 3;
bool havePadding2 = origLength == numOrig24BitValues * 3 + 2;
unsigned const numResultBytes = 4 * (numOrig24BitValues + havePadding);
char* result = new char[numResultBytes + 3]; // allow for trailing '/0'

// Map each full group of 3 input bytes into 4 output base-64 characters:
unsigned i;
for (i = 0; i < numOrig24BitValues; ++i)
{
result[4 * i + 0] = base64Char[(orig[3 * i] >> 2) & 0x3F];
result[4 * i + 1] = base64Char[(((orig[3 * i] & 0x3) << 4) | (orig[3 * i + 1] >> 4)) & 0x3F];
result[4 * i + 2] = base64Char[((orig[3 * i + 1] << 2) | (orig[3 * i + 2] >> 6)) & 0x3F];
result[4 * i + 3] = base64Char[orig[3 * i + 2] & 0x3F];
}

// Now, take padding into account. (Note: i == numOrig24BitValues)
if (havePadding)
{
result[4 * i + 0] = base64Char[(orig[3 * i] >> 2) & 0x3F];
if (havePadding2)
{
result[4 * i + 1] = base64Char[(((orig[3 * i] & 0x3) << 4) | (orig[3 * i + 1] >> 4)) & 0x3F];
result[4 * i + 2] = base64Char[(orig[3 * i + 1] << 2) & 0x3F];
}
else
{
result[4 * i + 1] = base64Char[((orig[3 * i] & 0x3) << 4) & 0x3F];
result[4 * i + 2] = '=';
}
result[4 * i + 3] = '=';
}

result[numResultBytes] = '\0';
return result;
}

int SmtpEmail::SMTPComunicate(const EmailInfo &info)
{

if (Connect() != 0)
{
return -1;
}
char * buffer = new char[1000];
memset(buffer, 0, 1000);

Read(buffer, 999);
if (strncmp(buffer, "220", 3) != 0) // not equal to 220
{
m_lastErrorMsg = buffer;
return 220;
}

//向服务器发送ehlo
std::string command = "ehlo EmailService\r\n";
Write(command.c_str(), command.length());

memset(buffer, 0, 1000);
Read(buffer, 999);
if (strncmp(buffer, "250", 3) != 0) // ehlo failed
{
m_lastErrorMsg = buffer;
return 250;
}

//进行登录验证
command = "AUTH PLAIN ";
std::string auth = '\0' + info.senderEmail + '\0' + info.password;
command += base64Encode(auth.data(), auth.size());
command += "\r\n";
Write(command.c_str(), command.length());

memset(buffer, 0, 1000);
Read(buffer, 999);
if (strncmp(buffer, "235", 3) != 0) // login failed
{
m_lastErrorMsg = buffer;
return 250;
}

//设置邮件发送者的邮箱地址
command = "mail FROM:<" + info.senderEmail + ">\r\n";
Write( command.c_str(), command.length());

memset(buffer, 0, 1000);
Read(buffer, 999);
if (strncmp(buffer, "250", 3) != 0) // not ok
{
m_lastErrorMsg = buffer;
return 250;
}

//设置邮件接收者的邮箱地址
command = "RCPT TO:<" + info.recipientEmail + ">\r\n";
Write( command.c_str(), command.length());

memset(buffer, 0, 1000);
Read( buffer, 999);
if (strncmp(buffer, "250", 3) != 0) // not ok
{
m_lastErrorMsg = buffer;
return 250;
}



//准备发送邮件
command = "data\r\n";
Write( command.c_str(), command.length());

memset(buffer, 0, 1000);
Read( buffer, 999);
if (strncmp(buffer, "354", 3) != 0) // not ready to receive message
{
m_lastErrorMsg = buffer;
return 354;
}

command = std::move(GetEmailBody(info));
Write( command.c_str(), command.length());

memset(buffer, 0, 1000);
Read(buffer, 999);
if (strncmp(buffer, "250", 3) != 0) // not ok
{
m_lastErrorMsg = buffer;
return 250;
}

//结束发送过程
delete buffer;
Write( "quit\r\n", 6);

DisConnect();
return 0;
}

std::string SmtpEmail::GetEmailBody(const EmailInfo &info)
{
//设定邮件的发送者名称、接收者名称、邮件主题,邮件内容。
std::ostringstream message;
message << "From: =?" << info.charset << "?b?" << base64Encode(info.sender.c_str(), info.sender.length()) << "?= <" << info.senderEmail << ">\r\n";

std::vector<std::string> vecToList;
for (auto item : info.recvList)
{
std::string to = "=?" + info.charset + "?b?" + base64Encode(item.second.c_str(), item.second.length()) + "?= <" + item.first + ">";
vecToList.push_back(to);
}

message << "To: " << join(vecToList, ",") << "\r\n";
message << "Subject: =?" << info.charset << "?b?" << base64Encode(info.subject.c_str(), info.subject.length()) << "?=\r\n";
message << "MIME-Version: 1.0\r\n";

if (info.ccEmail.size() > 0)
{
std::vector<std::string> vecCcList;
for (auto item : info.ccEmail)
{
std::string cc = "=?" + info.charset + "?b?" + base64Encode(item.first.c_str(), item.first.length()) + "?= <" + item.second + ">";
vecCcList.push_back(cc);
}
message << "Cc:" << join(vecCcList, ",") << "\r\n";
}

message << "Content-Type:multipart/mixed; boundary=\"Separator_ztq_000\"\r\n\r\n";
message << "--Separator_ztq_000\r\n";
message << "Content-Type: multipart/alternative; boundary=\"Separator_ztq_111\"\r\n\r\n";
message << "--Separator_ztq_111\r\n";
message << "Content-Type: " << "text/plain" << "; charset=\"" << info.charset << "\"\r\n";
message << "Content-Transfer-Encoding: base64\r\n";
message << "\r\n"; //此处要加,不然邮件正文无内容
message << base64Encode(info.message.c_str(), info.message.length());
message << "\r\n\r\n";
message << "--Separator_ztq_111--\r\n";
//---------------------文件部分处理--------------------------------------

for (auto item : info.attachment)
{
std::string filename = fileBasename(item);
std::string strContext = getFileContents(item.c_str());
if(strContext.empty())
{
std::cerr << "请检查传入的文件路径是否正确,此路径文件添加到附件失败,不发送此文件:" << std::endl;
std::cerr << item << std::endl;
}
else
{
std::string fileContext = base64Encode(strContext.c_str(), strContext.length());
std::string extension = GetFileExtension(filename);
std::string mimetype = GetMimeTypeFromFileName((char*)extension.c_str());
message << "--Separator_ztq_000\r\n";
message << "Content-Type: " << mimetype << "; name=\"" << filename << "\"\r\n";
message << "Content-Transfer-Encoding: base64\r\n";
message << "Content-Disposition: attachment; filename=\"" << filename << "\"\r\n\r\n";
message << fileContext + "\r\n\r\n"; //把读取到的文件内容以二进制形式发送
}
}
//-----------------------------------------------------------
message << "\r\n.\r\n";
return message.str();
}

SmtpEmail::SmtpEmail(const std::string& emailHost, const std::string& port) :m_host(emailHost), m_port(port)
{

}

SmtpEmail::~SmtpEmail()
{

}

int SmtpEmail::Read(void* buf, int num)
{
return recv(m_socketfd, (char*)buf, num, 0);
}
int SmtpEmail::Write(const void* buf, int num)
{
return send(m_socketfd, (char*)buf, num, 0);
}

int SmtpEmail::Connect()
{
#ifdef WIN32
//start socket connection
WSADATA wsadata;
WSAStartup(MAKEWORD(2, 2), &wsadata);
#endif

m_socketfd = socket(AF_INET, SOCK_STREAM, 0);
if (m_socketfd == INVALID_SOCKET)
{

m_lastErrorMsg = "Error on creating socket fd.";
return -1;
}

addrinfo inAddrInfo = { 0 };
inAddrInfo.ai_family = AF_INET;
inAddrInfo.ai_socktype = SOCK_STREAM;

printf("host:%s port:%s \n",m_host.c_str(), m_port.c_str());
if (getaddrinfo(m_host.c_str(), m_port.c_str(), &inAddrInfo, &m_addrinfo) != 0) // error occurs
{

m_lastErrorMsg = "Error on calling getadrrinfo().";
return -2;
}


if (connect(m_socketfd, m_addrinfo->ai_addr, m_addrinfo->ai_addrlen))
{

m_lastErrorMsg = "Error on calling connect().";
return -3;
}
return 0;
}

int SmtpEmail::DisConnect()
{
freeaddrinfo(m_addrinfo);
#ifdef WIN32
closesocket(m_socketfd);
#else
close(m_socketfd);
#endif
return 0;
}

/*********************************************************************************/


std::string SimpleSmtpEmail::GetEmailBody(const EmailInfo &info)
{
//设定邮件的发送者名称、接收者名称、邮件主题,邮件内容。
std::ostringstream message;
message << "From: =?" << info.charset << "?b?" << base64Encode(info.sender.c_str(), info.sender.length()) << "?= <" << info.senderEmail << ">\r\n";

std::vector<std::string> vecToList;
for (auto item : info.recvList)
{
std::string to = "=?" + info.charset + "?b?" + base64Encode(item.second.c_str(), item.second.length()) + "?= <" + item.first + ">";
vecToList.push_back(to);
}

message << "To: " << join(vecToList, ",") << "\r\n";
message << "Subject: =?" << info.charset << "?b?" << base64Encode(info.subject.c_str(), info.subject.length()) << "?=\r\n";
message << "MIME-Version: 1.0\r\n";

if (info.ccEmail.size() > 0)
{
std::vector<std::string> vecCcList;
for (auto item : info.ccEmail)
{
std::string cc = "=?" + info.charset + "?b?" + base64Encode(item.first.c_str(), item.first.length()) + "?= <" + item.second + ">";
vecCcList.push_back(cc);
}
message << "Cc:" << join(vecCcList, ",") << "\r\n";
}

message << "Content-Type:multipart/mixed; boundary=\"Separator_ztq_000\"\r\n\r\n";
message << "--Separator_ztq_000\r\n";
message << "Content-Type: multipart/alternative; boundary=\"Separator_ztq_111\"\r\n\r\n";
message << "--Separator_ztq_111\r\n";
message << "Content-Type: " << "text/plain" << "; charset=\"" << info.charset << "\"\r\n";
message << "Content-Transfer-Encoding: base64\r\n";
message << "\r\n"; //此处要加,不然邮件正文无内容
message << base64Encode(info.message.c_str(), info.message.length());
message << "\r\n\r\n";
message << "--Separator_ztq_111--\r\n";
//---------------------文件部分处理--------------------------------------

for (auto item : info.attachment)
{
std::string filename = fileBasename(item);
std::string strContext = getFileContents(item.c_str());
if(strContext.empty())
{
std::cerr << "请检查传入的文件路径是否正确,此路径文件添加到附件失败,不发送此文件:" << std::endl;
std::cerr << item << std::endl;
}
else
{
std::string fileContext = base64Encode(strContext.c_str(), strContext.length());
std::string extension = GetFileExtension(filename);
std::string mimetype = GetMimeTypeFromFileName((char*)extension.c_str());
message << "--Separator_ztq_000\r\n";
message << "Content-Type: " << mimetype << "; name=\"" << filename << "\"\r\n";
message << "Content-Transfer-Encoding: base64\r\n";
message << "Content-Disposition: attachment; filename=\"" << filename << "\"\r\n\r\n";
message << fileContext + "\r\n\r\n"; //把读取到的文件内容以二进制形式发送
}
}
//-----------------------------------------------------------
message << "\r\n.\r\n";
return message.str();
}

/***************************************************************************************************/

SslSmtpEmail::~SslSmtpEmail()
{

}

int SslSmtpEmail::Connect()
{
if (SmtpEmail::Connect() == 0)
{
SSL_library_init();
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
m_ctx = SSL_CTX_new(SSLv23_client_method());

m_ssl = SSL_new(m_ctx);
SSL_set_fd(m_ssl, m_socketfd);
SSL_connect(m_ssl);
}
return 0;
}

int SslSmtpEmail::DisConnect()
{
SSL_shutdown(m_ssl);
SSL_free(m_ssl);
SSL_CTX_free(m_ctx);

SmtpEmail::DisConnect();
return 0;
}



int SmtpEmail::SendEmail(const std::string& from, const std::string& passs, const std::string& to, const std::string& subject, const std::string& strMessage)
{

EmailInfo info;
info.charset = "UTF-8";
info.sender = from;
info.password = passs;
info.senderEmail = from;
info.recipientEmail = to;

info.recvList[to] = "";

info.subject = subject;
info.message = strMessage;

return SMTPComunicate(info);
}



int SmtpEmail::SendEmail(const std::string& from, const std::string& passs, const std::vector<std::string>& vecTo,
const std::string& subject, const std::string& strMessage, const std::vector<std::string>& attachment, const std::vector<std::string>& ccList)
{
std::vector<std::string> recvList;
recvList.insert(recvList.end(), vecTo.begin(), vecTo.end());
recvList.insert(recvList.end(), ccList.begin(), ccList.end());

for (auto& item : recvList)
{
EmailInfo info;
info.charset = "UTF-8";
info.sender = from;
info.password = passs;
info.senderEmail = from;;
info.recipientEmail = item;

for (auto item : vecTo)
{
info.recvList[item] = "";
}

info.subject = subject;
info.message = strMessage;

for (auto& item : ccList)
{
info.ccEmail[item] = item;
}

info.attachment = attachment;
if (SMTPComunicate(info) != 0)
{
return -1;
}
}
return 0;
}



int SslSmtpEmail::Read(void * buf, int num)
{

int ret = SSL_read(m_ssl, buf, num);

return ret;
}

int SslSmtpEmail::Write(const void * buf, int num)
{
return SSL_write(m_ssl, buf, num);
}


std::string SimpleSslSmtpEmail::GetEmailBody(const EmailInfo &info)
{
//设定邮件的发送者名称、接收者名称、邮件主题,邮件内容。
std::ostringstream message;
message << "From: =?" << info.charset << "?b?" << base64Encode(info.sender.c_str(), info.sender.length()) << "?= <" << info.senderEmail << ">\r\n";

std::vector<std::string> vecToList;
for (auto item : info.recvList)
{
std::string to = "=?" + info.charset + "?b?" + base64Encode(item.second.c_str(), item.second.length()) + "?= <" + item.first + ">";
vecToList.push_back(to);
}

message << "To: " << join(vecToList, ",") << "\r\n";
message << "Subject: =?" << info.charset << "?b?" << base64Encode(info.subject.c_str(), info.subject.length()) << "?=\r\n";
message << "MIME-Version: 1.0\r\n";

if (info.ccEmail.size() > 0)
{
std::vector<std::string> vecCcList;
for (auto item : info.ccEmail)
{
std::string cc = "=?" + info.charset + "?b?" + base64Encode(item.first.c_str(), item.first.length()) + "?= <" + item.second + ">";
vecCcList.push_back(cc);
}
message << "Cc:" << join(vecCcList, ",") << "\r\n";
}
message << "Content-Type:multipart/mixed; boundary=\"Separator_ztq_000\"\r\n\r\n";
message << "--Separator_ztq_000\r\n";
message << "Content-Type: multipart/alternative; boundary=\"Separator_ztq_111\"\r\n\r\n";
message << "--Separator_ztq_111\r\n";
message << "Content-Type: " << "text/plain" << "; charset=\"" << info.charset << "\"\r\n";
message << "Content-Transfer-Encoding: base64\r\n";
message << "\r\n"; //此处要加,不然邮件正文无内容
message << base64Encode(info.message.c_str(), info.message.length());
message << "\r\n\r\n";
message << "--Separator_ztq_111--\r\n";
//---------------------文件部分处理--------------------------------------

for (auto item : info.attachment)
{
std::string filename = fileBasename(item);
std::string strContext = getFileContents(item.c_str());
if(strContext.empty())
{
std::cerr << "请检查传入的文件路径是否正确,此路径文件添加到附件失败,不发送此文件:" << std::endl;
std::cerr << item << std::endl;
}
else
{
std::string fileContext = base64Encode(strContext.c_str(), strContext.length());
std::string extension = GetFileExtension(filename);
std::string mimetype = GetMimeTypeFromFileName((char*)extension.c_str());
message << "--Separator_ztq_000\r\n";
message << "Content-Type: " << mimetype << "; name=\"" << filename << "\"\r\n";
message << "Content-Transfer-Encoding: base64\r\n";
message << "Content-Disposition: attachment; filename=\"" << filename << "\"\r\n\r\n";
message << fileContext + "\r\n\r\n"; //把读取到的文件内容以二进制形式发送
}
}
//-----------------------------------------------------------
message << "\r\n.\r\n";
return message.str();
}

测试代码 main.cpp

SendEmail函数重载,支持基本的简单发送文本邮件,和支持附件、抄送、以及发给多人的发送方式,亲测能够发送成功,默认发送的编码是utf-8格式

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
#include <iostream>
#include <stdio.h>
#include "mail.h"

int main()
{

std::string from = "xxxx@163.com";
std::string passs ="xxxxx";//这里替换成自己的授权码
std::string to = "xxx@126.com";
std::string subject = "hello";
std::string strMessage = "test";


std::vector<std::string> vecTo; //发送列表
vecTo.push_back("xxx@126.com");

std::vector<std::string> ccList;
// ccList.push_back("xxx@xxx.com.cn");//抄送列表

std::vector<std::string> attachment;
attachment.push_back("mail.h");
attachment.push_back("/home/soft/Desktop/openwrt-sdk-imx6ul/1/mybuild.sh");


SmtpBase *base;
SimpleSmtpEmail m_mail("smtp.163.com","25");
base = &m_mail;
//base->SendEmail(from, passs, to, subject, strMessage);//普通的文本发送,明文发送

SimpleSslSmtpEmail m_ssl_mail("smtp.163.com","465");
base=&m_ssl_mail;
//base->SendEmail(from, passs, to, subject, strMessage);
base->SendEmail(from, passs,vecTo,subject,strMessage,attachment,ccList);//加密的发送,支持抄送、附件等

return 0;
}

邮箱收件箱
查看邮件头


实际收到的邮件

参考链接

C++基于Smtp协议发送邮件
SMTP基本原理与C++实现向多人发送邮件

后记

如果您觉得有帮助的话,请点个赞吧!有问题请留言评论,欢迎指出意见,谢谢。