Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.72/43: Рейтинг темы: голосов - 43, средняя оценка - 4.72
 Аватар для dr.curse
404 / 360 / 36
Регистрация: 11.10.2010
Сообщений: 1,907

Отправка файла по email

23.06.2011, 18:24. Показов 8603. Ответов 9
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Как отправить файл по email используя WinAPI или Qt.
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
23.06.2011, 18:24
Ответы с готовыми решениями:

Отправка письма на email
Здорова господа!!! Пишу щас программку которая должна отсылать письма на email, но ничего не получается. От что набрасал:#include...

Отлов нажатий клавиш в системе и отправка на email
Всем доброе время суток. Ребята нужна помощь... нада зделать клавиатурный шпион.. но так чтоб он присилал дание по майлу... тоисть с...

Отправка email-сообщения на smtp сервер с ssl
Помогите написать программу на c++, отправляющую email сообщение на smtp сервер с ssl.

9
 Аватар для jonson
240 / 213 / 84
Регистрация: 18.03.2010
Сообщений: 750
24.06.2011, 02:45
протокол SMTP и сокеты юзать надо. Погугли, должна быть масса примеров
0
бжни
 Аватар для alex_x_x
2473 / 1684 / 135
Регистрация: 14.05.2009
Сообщений: 7,162
24.06.2011, 02:55
да, мануал говорит
Класс QTcpSocket предоставляет интерфейс для TCP. Вы можете использовать QTcpSocket для создания стандартных сетевых протоколов таких как POP3, SMTP и NNTP, и для других.
Добавлено через 37 секунд
дальше какието готовые решения искать
0
 Аватар для xAtom
935 / 760 / 299
Регистрация: 09.12.2010
Сообщений: 1,346
Записей в блоге: 1
24.06.2011, 07:35
В WinAPI это сокеты, в Borland C++ Builder есть всё для отрпавки по SMTP протоколу по MAPI.

C++
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
        TMapiMessage MapiMessage;
        TMapiRecipDesc SenderDesc;
        TMapiRecipDesc RecipDesc;
        TMapiFileDesc  Files;
 
        memset((void*)&SenderDesc,'\0',sizeof(SenderDesc));
 
        SenderDesc.ulRecipClass = MAPI_ORIG;
        RecipDesc.ulReserved = 0;
        RecipDesc.ulRecipClass = MAPI_TO;
        RecipDesc.lpszName = "Алексею";
        RecipDesc.lpszAddress ="SMTP:pupkin@example.com";  // адрес получателя
        RecipDesc.ulEIDSize = 0;
        RecipDesc.lpEntryID = NULL;
 
        Files.ulReserved = 0;
        Files.flFlags = 0;
        Files.nPosition = -1;
        Files.lpszPathName = "X:\\lesson.doc";    // путь к файлу для отрпавки
        Files.lpszFileName = "lesson.doc";  // тут имя файла без пути
        Files.lpFileType = NULL;
 
        MapiMessage.ulReserved = 0;
        MapiMessage.lpszSubject = "Название тема сообщения";
        MapiMessage.lpszNoteText = "Текст соощения";
        MapiMessage.lpszMessageType = NULL;
        MapiMessage.lpszDateReceived = NULL;
        MapiMessage.lpszConversationID = NULL;
        MapiMessage.flFlags = 0;
        MapiMessage.lpOriginator = &SenderDesc;
        MapiMessage.nRecipCount = 1;
        MapiMessage.lpRecips = &RecipDesc;
        MapiMessage.nFileCount = 1;
        MapiMessage.lpFiles = &Files;
 
        MapiSendMail(0, (ULONG)Application->Handle, MapiMessage, MAPI_DIALOG | MAPI_LOGON_UI |  MAPI_NEW_SESSION, 0);
0
 Аватар для dr.curse
404 / 360 / 36
Регистрация: 11.10.2010
Сообщений: 1,907
24.06.2011, 11:09  [ТС]
xAtom, а как сделать при помощи сокетов?
0
 Аватар для igorrr37
2870 / 2017 / 991
Регистрация: 21.12.2010
Сообщений: 3,728
Записей в блоге: 15
24.06.2011, 19:24
Лучший ответ Сообщение было отмечено как решение

Решение

Юзайте лучше boost. Вот отправка с прикреплённым файлом.
C++
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
#include <iostream>
#include <ostream>
#include <string>
#include <fstream>
#include <iterator>
#include <windows.h> // CharToOem
#include <boost/asio.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/transform_width.hpp>
namespace iters=boost::archive::iterators;
typedef boost::asio::ip::tcp tcp;
typedef iters::base64_from_binary<iters::transform_width<std::string::const_iterator, 6, 8>>
    base64_t;
 
boost::asio::streambuf reqBuf, respBuf;
std::ostream reqStream(&reqBuf);
tcp::socket* psock;
 
void SendRequest(std::string s){
    reqStream<<s<<"\r\n";
    boost::asio::write(*psock, reqBuf);
}
 
std::size_t PrintResponse(){
    std::size_t len=boost::asio::read_until(*psock, respBuf, "\r\n");
    std::cout<<&respBuf;
    return len;
}
 
std::string Encode(const std::string& s){
    return std::string(base64_t(s.begin()), base64_t(s.end()));
}
 
int main(){
    try{
        std::ifstream ifs("1.txt"); // прикреплённый файл
        if(!ifs){std::cerr<<"File not found\n"; return 1;}
        std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()), encStr(Encode(str));
        ifs.close();
        // авторизация на ящик отправителя
        std::string login="name1", encLogin(Encode((login))); //имя
        std::string passw="passw1", encPassw(Encode(passw));  //пароль
        std::string host="smtp.mail.ru"; // почтовый сервер
        boost::asio::io_service io;
        tcp::resolver resolver(io);
        tcp::resolver::query query(host, "25"); //default smtp port
        tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
        tcp::resolver::iterator end;
        tcp::socket sock(io);
        psock=&sock;
        boost::system::error_code error = boost::asio::error::host_not_found;
        while (error && endpoint_iterator != end){
            sock.close();
            sock.connect(*endpoint_iterator++, error);
        }
        if (error) throw boost::system::system_error(error);
        PrintResponse();
        SendRequest("ehlo myhost");
        PrintResponse();
        SendRequest("auth login");//выбираем авторизацию по login
        PrintResponse();
        SendRequest(encLogin);
        PrintResponse();
        SendRequest(encPassw);
        PrintResponse();
        SendRequest("mail from:<name1@mail.ru>");//ящик отправителя
        PrintResponse();
        SendRequest("rcpt to:<name2@yandex.ru>");// ящик получателя
        PrintResponse();
        SendRequest("data");
        PrintResponse();
        SendRequest("from:<name1@mail.ru>");  //это
        SendRequest("to:<name2@yandex.ru>"); //не
        SendRequest("subject: Some subject"); //спам
        SendRequest("Mime-Version: 1.0");
        SendRequest("Content-Type: multipart/mixed; boundary=bound");
        SendRequest("\r\n--bound");
        SendRequest("Content-type: text/plain; charset=windows-1251");
        SendRequest("Content-Transfer-Encoding: quoted-printable\r\n");
        SendRequest("It's letter's text\r\nThis letter has attaching file.");//текст письма
        SendRequest("\r\n--bound");
        SendRequest("Content-Type: text/plain; name=file.txt");
        SendRequest("Content-Transfer-Encoding: base64");
        SendRequest("Content-Disposition: attachment\r\n");
        SendRequest(encStr);
        SendRequest("\r\n--bound--\r\n.");
        PrintResponse();
        SendRequest("quit");
        PrintResponse();
        sock.close();
    }
    catch (std::exception& e){
        char buf[512];
        CharToOem(e.what(), buf);
        std::cout << "Exception: " << buf << "\n";
    }
    return 0;
}
5
78 / 78 / 9
Регистрация: 26.12.2011
Сообщений: 217
25.02.2012, 18:42
Цитата Сообщение от igorrr37 Посмотреть сообщение
Юзайте лучше boost. Вот отправка с прикреплённым файлом.
C++
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
#include <iostream>
#include <ostream>
#include <string>
#include <fstream>
#include <iterator>
#include <windows.h> // CharToOem
#include <boost/asio.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/transform_width.hpp>
namespace iters=boost::archive::iterators;
typedef boost::asio::ip::tcp tcp;
typedef iters::base64_from_binary<iters::transform_width<std::string::const_iterator, 6, 8>>
    base64_t;
 
boost::asio::streambuf reqBuf, respBuf;
std::ostream reqStream(&reqBuf);
tcp::socket* psock;
 
void SendRequest(std::string s){
    reqStream<<s<<"\r\n";
    boost::asio::write(*psock, reqBuf);
}
 
std::size_t PrintResponse(){
    std::size_t len=boost::asio::read_until(*psock, respBuf, "\r\n");
    std::cout<<&respBuf;
    return len;
}
 
std::string Encode(const std::string& s){
    return std::string(base64_t(s.begin()), base64_t(s.end()));
}
 
int main(){
    try{
        std::ifstream ifs("1.txt"); // прикреплённый файл
        if(!ifs){std::cerr<<"File not found\n"; return 1;}
        std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()), encStr(Encode(str));
        ifs.close();
        // авторизация на ящик отправителя
        std::string login="name1", encLogin(Encode((login))); //имя
        std::string passw="passw1", encPassw(Encode(passw));  //пароль
        std::string host="smtp.mail.ru"; // почтовый сервер
        boost::asio::io_service io;
        tcp::resolver resolver(io);
        tcp::resolver::query query(host, "25"); //default smtp port
        tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
        tcp::resolver::iterator end;
        tcp::socket sock(io);
        psock=&sock;
        boost::system::error_code error = boost::asio::error::host_not_found;
        while (error && endpoint_iterator != end){
            sock.close();
            sock.connect(*endpoint_iterator++, error);
        }
        if (error) throw boost::system::system_error(error);
        PrintResponse();
        SendRequest("ehlo myhost");
        PrintResponse();
        SendRequest("auth login");//выбираем авторизацию по login
        PrintResponse();
        SendRequest(encLogin);
        PrintResponse();
        SendRequest(encPassw);
        PrintResponse();
        SendRequest("mail from:<name1@mail.ru>");//ящик отправителя
        PrintResponse();
        SendRequest("rcpt to:<name2@yandex.ru>");// ящик получателя
        PrintResponse();
        SendRequest("data");
        PrintResponse();
        SendRequest("from:<name1@mail.ru>");  //это
        SendRequest("to:<name2@yandex.ru>"); //не
        SendRequest("subject: Some subject"); //спам
        SendRequest("Mime-Version: 1.0");
        SendRequest("Content-Type: multipart/mixed; boundary=bound");
        SendRequest("\r\n--bound");
        SendRequest("Content-type: text/plain; charset=windows-1251");
        SendRequest("Content-Transfer-Encoding: quoted-printable\r\n");
        SendRequest("It's letter's text\r\nThis letter has attaching file.");//текст письма
        SendRequest("\r\n--bound");
        SendRequest("Content-Type: text/plain; name=file.txt");
        SendRequest("Content-Transfer-Encoding: base64");
        SendRequest("Content-Disposition: attachment\r\n");
        SendRequest(encStr);
        SendRequest("\r\n--bound--\r\n.");
        PrintResponse();
        SendRequest("quit");
        PrintResponse();
        sock.close();
    }
    catch (std::exception& e){
        char buf[512];
        CharToOem(e.what(), buf);
        std::cout << "Exception: " << buf << "\n";
    }
    return 0;
}
У меня данный пример вылетает с ошибкой string iterator not dereferencable.
Как я понимаю, не может разыменовать. Это только у меня так или как? ))
0
 Аватар для igorrr37
2870 / 2017 / 991
Регистрация: 21.12.2010
Сообщений: 3,728
Записей в блоге: 15
25.02.2012, 19:09
работает
Миниатюры
Отправка файла по email  
0
 Аватар для igorrr37
2870 / 2017 / 991
Регистрация: 21.12.2010
Сообщений: 3,728
Записей в блоге: 15
25.02.2012, 22:04
Лучший ответ Сообщение было отмечено как решение

Решение

для VS
C++
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
#include <stdafx.h>
#include <iostream>
#include <ostream>
#include <string>
#include <fstream>
#include <bitset>
#include <iterator>
#include <boost/asio.hpp>
#include <windows.h> // CharToOem
typedef boost::asio::ip::tcp tcp;
 
boost::asio::streambuf reqBuf, respBuf;
std::ostream reqStream(&reqBuf);
tcp::socket* psock;
 
void SendRequest(std::string s){
    reqStream<<s<<"\r\n";
    boost::asio::write(*psock, reqBuf);
}
 
std::size_t PrintResponse(){
    std::size_t len=boost::asio::read_until(*psock, respBuf, "\r\n");
    std::cout<<&respBuf;
    return len;
}
 
std::string Encode(const std::string& s)
{
    std::size_t size = s.size();
    std::string ini("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), out, bits;
    char buf[3];
    int la = 0, lb = 0;
    for(int j = 0; j < size; j += 3)
    {
        bits.clear();
        for(int i = 0; i < 3; ++i) buf[i] = '\0';
        buf[0] = s[j];
        if(j + 1 < size) buf[1] = s[j + 1];
        else la = 1;
        if(j + 2 < size) buf[2] = s[j + 2];
        else lb = 1;
        for(int k = 0; k < 3; ++k)
        {
            for(int l = 7; l >= 0; --l)
            {
                bits.push_back((buf[k] >> l) & 1 ? '1' : '0');
            }
        }
        //std::cout << bits << std::endl;
        for(int l = 0; l < 4; ++l)
        {
            int m = (l + 1) * 6 - 1, n = l * 6;
            std::bitset<6> b(std::string(&bits[n], &bits[m + 1]));
            //std::cout << b.to_ulong() << std::endl;
            if((l == 2 && la) || (l == 3 && lb))
            {
                out.push_back('=');
            }
            else out.push_back(ini[b.to_ulong()]);
        }
    }
    //std::cout << "out : " << out << std::endl;
    return out;
}
 
int main(){
    try{
        std::ifstream ifs("1.txt"); // прикреплённый файл
        if(!ifs){std::cerr<<"File not found\n"; return 1;}
        std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()), encStr(Encode(str));
        ifs.close();
        // авторизация на ящик отправителя
        std::string login="name1", encLogin(Encode((login))); //имя
        std::string passw="passw1", encPassw(Encode(passw));  //пароль
        std::string host="smtp.mail.ru"; // почтовый сервер
        boost::asio::io_service io;
        tcp::resolver resolver(io);
        tcp::resolver::query query(host, "25"); //default smtp port
        tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
        tcp::resolver::iterator end;
        tcp::socket sock(io);
        psock=&sock;
        boost::system::error_code error = boost::asio::error::host_not_found;
        while (error && endpoint_iterator != end){
            sock.close();
            sock.connect(*endpoint_iterator++, error);
        }
        if (error) throw boost::system::system_error(error);
        PrintResponse();
        SendRequest("ehlo myhost");
        PrintResponse();
        SendRequest("auth login");//выбираем авторизацию по login
        PrintResponse();
        SendRequest(encLogin);
        PrintResponse();
        SendRequest(encPassw);
        PrintResponse();
        SendRequest("mail from:<name1@mail.ru>");//ящик отправителя
        PrintResponse();
        SendRequest("rcpt to:<name2@yandex.ru>");// ящик получателя
        PrintResponse();
        SendRequest("data");
        PrintResponse();
        SendRequest("from:<name1@mail.ru>");  //это
        SendRequest("to:<name2@yandex.ru>"); //не
        SendRequest("subject: Some subject"); //спам
        SendRequest("Mime-Version: 1.0");
        SendRequest("Content-Type: multipart/mixed; boundary=bound");
        SendRequest("\r\n--bound");
        SendRequest("Content-type: text/plain; charset=windows-1251");
        SendRequest("Content-Transfer-Encoding: quoted-printable\r\n");
        SendRequest("It's letter's text\r\nThis letter has attaching file.");//текст письма
        SendRequest("\r\n--bound");
        SendRequest("Content-Type: text/plain; name=file.txt");
        SendRequest("Content-Transfer-Encoding: base64");
        SendRequest("Content-Disposition: attachment\r\n");
        SendRequest(encStr);
        SendRequest("\r\n--bound--\r\n.");
        PrintResponse();
        SendRequest("quit");
        PrintResponse();
        sock.close();
        std::cin.sync();
        std::cin.get();
    }
    catch (std::exception& e){
        char buf[512];
        CharToOemA(e.what(), buf);
        std::cout << "Exception: " << buf << "\n";
    }
    return 0;
}
4
 Аватар для igorrr37
2870 / 2017 / 991
Регистрация: 21.12.2010
Сообщений: 3,728
Записей в блоге: 15
04.01.2019, 09:32
Обновлено с учетом ssl/tls
Для работы кода должен быть установлен OpenSSL
сборка OpenSSL
C++
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
#include "C:/boost_1_68_0_VS2017/libs/beast/example/common/root_certificates.hpp" // прописать свой путь
#include <boost/beast/core.hpp>
#include <boost/beast/core/detail/base64.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl/error.hpp>
#include <boost/asio/ssl/stream.hpp>
#include <boost/asio/streambuf.hpp>
#include <boost/asio/read_until.hpp>
#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <filesystem>
 
using tcp = boost::asio::ip::tcp;       // from <boost/asio/ip/tcp.hpp>
namespace ssl = boost::asio::ssl;       // from <boost/asio/ssl.hpp>
namespace bd = boost::beast::detail;
namespace fs = std::experimental::filesystem;
 
ssl::stream<tcp::socket>* pStream;
boost::asio::streambuf buf;
std::ostream reqStream(&buf);
 
std::size_t PrintResponse()
{
    std::size_t len = boost::asio::read_until(*pStream, buf, "\r\n");
    std::cout << &buf;
    return len;
}
 
std::size_t SendRequest(std::string const& s)
{
    reqStream << s << "\r\n";
    return boost::asio::write(*pStream, buf);
}
 
// отправка письма с прикреплённым файлом с ящика mail.ru на ящик yandex.ru
int main()
{
    system("chcp 1251");
    try
    {
        auto const host = "smtp.mail.ru";
        auto const port = "465"; // при отправке с mail.ru
 
        // The io_context is required for all I/O
        boost::asio::io_context ioc;
 
        // The SSL context is required, and holds certificates
        ssl::context ctx{ ssl::context::sslv23_client };
 
        // This holds the root certificate used for verification
        load_root_certificates(ctx);
 
        // Verify the remote server's certificate
        //ctx.set_verify_mode(ssl::verify_peer);
 
        // These objects perform our I/O
        tcp::resolver resolver{ ioc };
        ssl::stream<tcp::socket> stream{ ioc, ctx };
        pStream = &stream;
 
        // Set SNI Hostname (many hosts need this to handshake successfully)
        if (!SSL_set_tlsext_host_name(stream.native_handle(), host))
        {
            boost::system::error_code ec{ static_cast<int>(::ERR_get_error()), boost::asio::error::get_ssl_category() };
            throw boost::system::system_error{ ec };
        }
 
        // Look up the domain name
        auto const results = resolver.resolve(host, port);
 
        // Make the connection on the IP address we get from a lookup
        boost::asio::connect(stream.next_layer(), results.begin(), results.end());
 
        // Perform the SSL handshake
        stream.handshake(ssl::stream_base::client);
 
        // прикреплённый файл
        std::vector<uint8_t> vfa;
        std::string faName{ "in.jpg" };
        std::ifstream ifs{ faName, std::ios::binary };
        if (ifs.is_open())
        {
            auto fs = fs::file_size(faName);
            vfa.assign(std::istreambuf_iterator<char>{ifs.rdbuf()}, {});
            auto vs = vfa.size();
 
            ifs.close();
        }
        else
        {
            throw std::exception{("Unable to open attached file " + faName + "\n").c_str()};
        }
 
        std::string name{"loginSender"}; // имя пользователя ящика отправителя
        std::string passw{"passwordSender"}; // пароль ящика отправителя
 
        std::string encName = bd::base64_encode(name);
        std::string encPassw = bd::base64_encode(passw);
        std::string encFa = bd::base64_encode(vfa.data(), vfa.size());
 
        PrintResponse();
        SendRequest("ehlo myhost");
        PrintResponse();
        SendRequest("auth login");
        PrintResponse();
        SendRequest(encName);
        PrintResponse();
        SendRequest(encPassw);
        PrintResponse();
        SendRequest("mail from:<loginSender@mail.ru>");//ящик отправителя
        PrintResponse();
        SendRequest("rcpt to:<loginRecipient@yandex.ru>");// ящик получателя
        PrintResponse();
        SendRequest("data");
        PrintResponse();
        SendRequest("from:<loginSender@mail.ru>");  //это
        SendRequest("to:<loginRecipient@yandex.ru>"); //не
        SendRequest("subject: Some subject"); //спам
        SendRequest("Mime-Version: 1.0");
        SendRequest("Content-Type: multipart/mixed; boundary=bound");
        SendRequest("\r\n--bound");
        SendRequest("Content-type: text/plain; charset=windows-1251");
        SendRequest("Content-Transfer-Encoding: quoted-printable\r\n");
        SendRequest("It's letter's text\r\nThis letter has attached file."); //текст письма
        SendRequest("\r\n--bound");
        SendRequest("Content-Type: text/plain; name=" + faName + "");
        SendRequest("Content-Transfer-Encoding: base64");
        SendRequest("Content-Disposition: attachment\r\n");
        SendRequest(encFa);
        SendRequest("\r\n--bound--\r\n.");
        PrintResponse();
        SendRequest("quit");
        PrintResponse();
 
        // Gracefully close the stream
        boost::system::error_code ec;
        stream.shutdown(ec);
        if (ec == boost::asio::error::eof)
        {
            // Rationale:
            // http://stackoverflow.com/questions/25587403/boost-asio-ssl-async-shutdown-always-finishes-with-an-error
            ec.assign(0, ec.category());
        }
        if (ec)
            throw boost::system::system_error{ ec };
 
        // If we get here then the connection is closed gracefully
 
        
    }
    catch (std::exception const& e)
    {
        std::cerr << "Error: " << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
04.01.2019, 09:32
Помогаю со студенческими работами здесь

Подскажите литературу: как реализуется отправка email и sms?
Здравствуйте, хочу разобраться как реализуется отправка email и sms, есть литература на эту тему ?

Пиши прогу которая вытаскивает email адреса из файла.
Добрый день. Хочу реализовать программку в c++ builder, которая вытаскивает из txt файла все email адреса и записывает их в отдельный...

Отправка файла по email
Подскажите пожалуйста, методы или средства PL/SQL с помошью которых можно отправить файл вложением в письме по e-mail.

Отправка файла на email
Как отправить письмо с вложенным файлом (к примеру 1.txt) на E-mail??? //Если можете напишите исходник от А до Я...

Отправка файла на email
Доброго времени суток форумчане. Нужно отправить файл на почтовик. Ошибка в TIdAttachment. C++ builder XE3 Кто может помочь вот проект:


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
10
Ответ Создать тему
Новые блоги и статьи
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост.
Programma_Boinc 28.12.2025
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост. Налог на собак: https:/ / **********/ gallery/ V06K53e Финансовый отчет в Excel: https:/ / **********/ gallery/ bKBkQFf Пост отсюда. . .
Кто-нибудь знает, где можно бесплатно получить настольный компьютер или ноутбук? США.
Programma_Boinc 26.12.2025
Нашел на реддите интересную статью под названием Anyone know where to get a free Desktop or Laptop? Ниже её машинный перевод. После долгих разбирательств я наконец-то вернула себе. . .
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка.
Programma_Boinc 23.12.2025
Рецензия / Мнение/ Перевод Нашел на реддите интересную статью под названием The Thinkpad X220 Tablet is the best budget school laptop period . Ниже её машинный перевод. Thinkpad X220 Tablet —. . .
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 05.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru