summaryrefslogtreecommitdiff
path: root/src/message/sender.cpp
blob: 343153503d847aac6343906b753644f7c2730199 (plain)
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
#include <cstring>

#include "sender.hpp"
#include "builder/date.hpp"
#include "builder/mail_to.hpp"
#include "builder/cc.hpp"
#include "builder/subject.hpp"
#include "builder/text.hpp"
#include "builder/from.hpp"
#include "logger/logger_set.hpp"

namespace smtp::message
{
    static std::string mText;

    //
    //Public methods
    //

    bool Sender::Send( manage::Settings const& settings_storage, std::string const& mail_from,
                       general::MailsSet const& mails_to, std::string const& subject,
                       std::string const& text )
    {
        static const std::string METHOD_NAME = "Send message";

        if( mails_to.empty() )
        {
            return false;
        }

        CURLcode result = CURLE_OK;
        curl_slist* recipients = nullptr;
        WriteThis upload_ctx{};
        auto curl = curl_easy_init();
        //TODO сделать инициализацию через регистратор инициализаторов
        if( !InitCurl( curl, upload_ctx, settings_storage, mail_from ))
        {
            logger::LoggerSet::GetInstance()->LogError( METHOD_NAME, "Error to initializate message service" );
            return false;
        }
        FillRecipients( curl, recipients, mails_to);
        UpdateMailText( mails_to, settings_storage.GetUserName(), subject, text );
        result = curl_easy_perform( curl );
        if( result != CURLE_OK )
        {
            std::string message = "Error to send messge: " + std::string( curl_easy_strerror( result ));
            logger::LoggerSet::GetInstance()->LogError( METHOD_NAME, message );
            return false;
        }
        curl_slist_free_all( recipients );
        curl_easy_cleanup( curl );
        return true;
	}

	//
	//Private methods
	//
    bool smtp::message::Sender::InitCurl( CURL* curl, WriteThis const& upload_ctx,
                                          manage::Settings const& settings_storage,
                                          std::string const& mail_from )
	{
		if( !curl )
		{
			return false;
		}
		
        if( settings_storage.IsNeedAuth())
		{
            curl_easy_setopt( curl, CURLOPT_USERNAME, settings_storage.GetUserName().c_str());
            curl_easy_setopt( curl, CURLOPT_PASSWORD, settings_storage.GetPassword().c_str());
		}

        curl_easy_setopt( curl, CURLOPT_URL, GetHostPortData( settings_storage ).c_str());

        settings_storage.IsNeedSsl() ? curl_easy_setopt( curl, CURLOPT_USE_SSL, ( long ) CURLUSESSL_ALL ) :
									   curl_easy_setopt( curl, CURLOPT_USE_SSL, ( long ) CURLUSESSL_NONE );

		curl_easy_setopt( curl, CURLOPT_MAIL_FROM, mail_from.c_str());

		curl_easy_setopt( curl, CURLOPT_READFUNCTION, ReadCallBack );
		curl_easy_setopt( curl, CURLOPT_READDATA, &upload_ctx );
        curl_easy_setopt( curl, CURLOPT_UPLOAD, 1L );
        curl_easy_setopt( curl, CURLOPT_NOPROGRESS, 1L );

		return true;
	}

    void Sender::FillRecipients( CURL* curl, curl_slist* recipients, general::MailsSet const& mails_to )
    {
        for( const auto& recipient: mails_to )
        {
            recipients = curl_slist_append( recipients, recipient.c_str());
        }

        curl_easy_setopt( curl, CURLOPT_MAIL_RCPT, recipients );
    }

	void
    Sender::UpdateMailText( general::MailsSet const& mails_to,
                            std::string const& mail_from,
                            std::string const& subject,
                            std::string const& text ) const
	{
        auto text_decorator = std::make_shared < builder::Text >( text );
        text_decorator->Apply( std::make_shared < builder::Date >())
                .Apply( std::make_shared < builder::Subject >( subject ))
                .Apply( std::make_shared < builder::Cc >( mails_to ))
                .Apply( std::make_shared < builder::From >( mail_from ))
                .Apply( std::make_shared < builder::MailTo >( mails_to ));
		mText = text_decorator->Get();
	}



    std::string Sender::GetHostPortData( manage::Settings const& settings_storage ) const
	{
        auto result = "smtp://" + settings_storage.GetHost();
        if( !settings_storage.GetPort().empty())
		{
            result += ":" + settings_storage.GetPort();
		}
		return result;
	}

	//TODO Надо убрать этот ужас. Без статики!!!
	size_t Sender::ReadCallBack( void* ptr, size_t size, size_t nmemb, void* userp )
	{
		auto pooh = reinterpret_cast<WriteThis*>( userp );
		if( size * nmemb < 1 || pooh->counter++ > 0 )
		{
			return 0;
		}
		memcpy( ptr, mText.c_str(), mText.size());
		return mText.size();
	}
}