2 Copyright (C) 2015 Carl Hetherington <cth@carlh.net>
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 #include "compose.hpp"
25 #include "exceptions.h"
26 #include <curl/curl.h>
27 #include <boost/algorithm/string.hpp>
28 #include <boost/date_time/c_local_time_adjustor.hpp>
29 #include <boost/foreach.hpp>
34 using std::stringstream;
39 using boost::shared_ptr;
41 Emailer::Emailer (string from, string to, string subject, string body)
48 boost::algorithm::replace_all (_body, "\n", "\r\n");
52 Emailer::add_cc (string cc)
58 Emailer::add_bcc (string bcc)
64 Emailer::add_attachment (boost::filesystem::path file, string name, string mime_type)
69 a.mime_type = mime_type;
70 _attachments.push_back (a);
74 curl_data_shim (void* ptr, size_t size, size_t nmemb, void* userp)
76 return reinterpret_cast<Emailer*>(userp)->get_data (ptr, size, nmemb);
80 Emailer::get_data (void* ptr, size_t size, size_t nmemb)
82 size_t const t = min (_email.length() - _offset, size * nmemb);
83 memcpy (ptr, _email.substr(_offset, size * nmemb).c_str(), size * nmemb);
89 Emailer::send (shared_ptr<Job> job)
92 time_t now = time (0);
93 strftime (date_buffer, sizeof(date_buffer), "%a, %d %b %Y %H:%M:%S ", localtime (&now));
95 boost::posix_time::ptime const utc_now = boost::posix_time::second_clock::universal_time ();
96 boost::posix_time::ptime const local_now = boost::date_time::c_local_adjustor<boost::posix_time::ptime>::utc_to_local (utc_now);
97 boost::posix_time::time_duration offset = local_now - utc_now;
98 sprintf (date_buffer + strlen(date_buffer), "%s%02d%02d", (offset.hours() >= 0 ? "+" : "-"), abs (offset.hours()), offset.minutes());
102 email << "Date: " << date_buffer << "\r\n"
103 << "To: " << _to << "\r\n"
104 << "From: " << _from << "\r\n";
107 email << "Cc: " << address_list (_cc);
110 if (!_bcc.empty ()) {
111 email << "Bcc: " << address_list (_bcc);
114 string const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
116 for (int i = 0; i < 32; ++i) {
117 boundary += chars[rand() % chars.length()];
120 if (!_attachments.empty ()) {
121 email << "MIME-Version: 1.0\r\n"
122 << "Content-Type: multipart/alternative; boundary=" << boundary << "\r\n";
125 email << "Subject: " << _subject << "\r\n"
126 << "User-Agent: DCP-o-matic\r\n"
129 if (!_attachments.empty ()) {
130 email << "--" << boundary << "\r\n"
131 << "Content-Type: text/plain; charset=utf-8\r\n\r\n";
136 BOOST_FOREACH (Attachment i, _attachments) {
137 email << "\r\n\r\n--" << boundary << "\r\n"
138 << "Content-Type: " << i.mime_type << "; name=" << i.name << "\r\n"
139 << "Content-Transfer-Encoding: Base64\r\n"
140 << "Content-Disposition: attachment; filename=" << i.name << "\r\n\r\n";
142 BIO* b64 = BIO_new (BIO_f_base64());
144 BIO* bio = BIO_new (BIO_s_mem());
145 bio = BIO_push (b64, bio);
148 BIO_write (bio, data.data().get(), data.size());
149 (void) BIO_flush (bio);
152 long int bytes = BIO_get_mem_data (bio, &out);
153 email << string (out, bytes);
158 if (!_attachments.empty ()) {
159 email << "\r\n--" << boundary << "--\r\n";
162 _email = email.str ();
164 curl_global_init (CURL_GLOBAL_DEFAULT);
166 CURL* curl = curl_easy_init ();
168 throw NetworkError ("Could not initialise libcurl");
171 CURLM* mcurl = curl_multi_init ();
173 throw NetworkError ("Could not initialise libcurl");
176 curl_easy_setopt (curl, CURLOPT_URL, String::compose (
178 Config::instance()->mail_server().c_str(),
179 Config::instance()->mail_port()
182 if (!Config::instance()->mail_user().empty ()) {
183 curl_easy_setopt (curl, CURLOPT_USERNAME, Config::instance()->mail_user().c_str());
185 if (!Config::instance()->mail_password().empty ()) {
186 curl_easy_setopt (curl, CURLOPT_PASSWORD, Config::instance()->mail_password().c_str());
189 curl_easy_setopt (curl, CURLOPT_MAIL_FROM, _from.c_str());
191 struct curl_slist* recipients = curl_slist_append (0, _to.c_str());
192 BOOST_FOREACH (string i, _cc) {
193 recipients = curl_slist_append (recipients, i.c_str());
195 BOOST_FOREACH (string i, _bcc) {
196 recipients = curl_slist_append (recipients, i.c_str());
199 curl_easy_setopt (curl, CURLOPT_MAIL_RCPT, recipients);
201 curl_easy_setopt (curl, CURLOPT_READFUNCTION, curl_data_shim);
202 curl_easy_setopt (curl, CURLOPT_READDATA, this);
203 curl_easy_setopt (curl, CURLOPT_UPLOAD, 1L);
205 curl_easy_setopt (curl, CURLOPT_USE_SSL, (long) CURLUSESSL_TRY);
206 curl_easy_setopt (curl, CURLOPT_SSL_VERIFYPEER, 0L);
207 curl_easy_setopt (curl, CURLOPT_SSL_VERIFYHOST, 0L);
208 curl_easy_setopt (curl, CURLOPT_VERBOSE, 1L);
210 _notes_buffer.reset (new char[65536]);
211 FILE* notes = fmemopen (_notes_buffer.get(), 65536, "w");
212 curl_easy_setopt (curl, CURLOPT_STDERR, notes);
214 curl_multi_add_handle (mcurl, curl);
216 time_t start = time (0);
218 int still_running = 1;
219 curl_multi_perform (mcurl, &still_running);
221 while (still_running) {
231 struct timeval timeout;
235 long curl_timeout = -1;
236 curl_multi_timeout (mcurl, &curl_timeout);
237 if (curl_timeout >= 0) {
238 timeout.tv_sec = curl_timeout / 1000;
239 if (timeout.tv_sec > 1) {
242 timeout.tv_usec = (curl_timeout % 1000) * 1000;
247 CURLMcode mc = curl_multi_fdset (mcurl, &fdread, &fdwrite, &fdexcep, &maxfd);
249 if (mc != CURLM_OK) {
251 throw KDMError (String::compose ("Failed to send KDM email to %1", _to));
256 #ifdef DCPOMATIC_WINDOWS
260 struct timeval wait = { 0, 100 * 1000};
261 rc = select (0, 0, 0, 0, &wait);
264 rc = select (maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout);
268 throw KDMError ("Failed to send KDM email");
271 mc = curl_multi_perform (mcurl, &still_running);
272 if (mc != CURLM_OK) {
274 throw KDMError (String::compose ("Failed to send KDM email (%1)", curl_multi_strerror (mc)));
278 job->set_progress_unknown ();
281 if ((time(0) - start) > 10) {
283 throw KDMError (_("Failed to send KDM email (timed out)"));
289 CURLMsg* m = curl_multi_info_read (mcurl, &messages);
290 if (m && m->data.result != CURLE_OK) {
292 throw KDMError (String::compose ("Failed to send KDM email (%1)", curl_easy_strerror (m->data.result)));
294 } while (messages > 0);
296 /* XXX: we should do this stuff when an exception is thrown, but curl_multi_remove_handle
297 seems to hang if we try that.
300 curl_slist_free_all (recipients);
301 curl_multi_remove_handle (mcurl, curl);
302 curl_multi_cleanup (mcurl);
303 curl_easy_cleanup (curl);
304 curl_global_cleanup ();
310 Emailer::address_list (list<string> addresses)
313 BOOST_FOREACH (string i, addresses) {
317 return o.substr (0, o.length() - 2);
321 Emailer::notes () const
323 return string (_notes_buffer.get());