#include #include #include #include #include #include #include #include #include #include #include // Сетевые сокеты #include #include #include #include #include #include "utl_mail.hpp" extern "C" { #include "utils/builtins.h" #include "utils/elog.h" #include "utils/guc.h" #include "utils/varlena.h" extern char *SmtpHostPort; } // ---------- Вспомогательные ---------- namespace { static std::mutex g_cfg_mtx; static std::string g_override_server; // host[:port] static std::string g_override_helo; // HELO/EHLO /// @brief Параметры SMTP (хост, порт, таймауты) /// Можно задать SET qdb.smtp_out_server = '127.0.0.1:2525'; struct SmtpConfig { std::string host; std::string port{"25"}; std::string helo{"localhost"}; }; /// @brief Конвертирует PostgreSQL text* в std::string (UTF-8). static std::string to_std_string(text* t) { if (!t) return {}; char* c = text_to_cstring(t); std::string s(c ? c : ""); if (c) pfree(c); return s; } /// @brief Возвращает строку без пробелов в начале/конце static std::string trim_copy(const std::string& s) { auto b = std::find_if_not(s.begin(), s.end(), [](unsigned char c){ return std::isspace(c); }); auto e = std::find_if_not(s.rbegin(), s.rend(), [](unsigned char c){ return std::isspace(c); }).base(); if (b >= e) return {}; return std::string(b, e); } /// @brief to-lower без локали static std::string lower_copy(const std::string& s) { std::string r; r.reserve(s.size()); for (unsigned char c : s) r.push_back(std::tolower(c)); return r; } /// @brief Считывает значение параметра key из postgresql.conf (без include’ов). /// Понимает комментарии '#', пробелы, а также кавычки вокруг значения. static std::string read_conf_value(const std::string& path, const std::string& key) { std::ifstream in(path); if (!in.good()) return {}; const std::string key_lc = lower_copy(key); std::string line; while (std::getline(in, line)) { // убрать \r если есть if (!line.empty() && line.back() == '\r') line.pop_back(); // отрезать комментарий auto hash = line.find('#'); if (hash != std::string::npos) line.erase(hash); line = trim_copy(line); if (line.empty()) continue; auto eq = line.find('='); if (eq == std::string::npos) continue; std::string lhs = trim_copy(line.substr(0, eq)); std::string rhs = trim_copy(line.substr(eq + 1)); if (lower_copy(lhs) != key_lc) continue; // убрать возможные одинарные/двойные кавычки if (rhs.size() >= 2 && ((rhs.front() == '\'' && rhs.back() == '\'') || (rhs.front() == '"' && rhs.back() == '"'))) { rhs = rhs.substr(1, rhs.size() - 2); } return trim_copy(rhs); } return {}; } /// @brief Разбор host[:port], умеет форму [IPv6]:port. Если port не задан — берёт def_port. static std::pair parse_host_port(const std::string& v, const std::string& def_port) { std::string s = trim_copy(v); std::string host, port; if (s.empty()) return {host, def_port}; if (!s.empty() && s.front() == '[') { auto rb = s.find(']'); if (rb != std::string::npos) { host = s.substr(1, rb - 1); if (rb + 1 < s.size() && s[rb + 1] == ':') { port = trim_copy(s.substr(rb + 2)); } } else { // нет закрывающей скобки — fallback: взять всё как host host = s; } } else { // взять последний ':' как разделитель порта (чтобы не ломать hostnames с двоеточиями в будущем) auto pos = s.rfind(':'); if (pos == std::string::npos) { host = s; } else { host = trim_copy(s.substr(0, pos)); port = trim_copy(s.substr(pos + 1)); } } if (host.empty()) host = s; if (port.empty()) port = def_port; return {host, port}; } /// @brief Делит CSV-строку на элементы (с триммингом). static std::vector split_csv(const std::string& s) { std::vector out; std::string cur; std::stringstream ss(s); while (std::getline(ss, cur, ',')) { cur = trim_copy(cur); if (!cur.empty()) out.push_back(cur); } return out; } /// @brief Проверяет, содержит ли строка только ASCII. static bool is_ascii(const std::string& s) { return std::all_of(s.begin(), s.end(), [](unsigned char c){ return c < 0x80; }); } /// @brief Кодирует данные в Base64. static std::string base64(const unsigned char* data, size_t len) { static const char* B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; std::string out; out.reserve(((len+2)/3)*4 + len/57*2); size_t i=0; while (i+3 <= len) { unsigned v = (data[i]<<16) | (data[i+1]<<8) | (data[i+2]); out.push_back(B64[(v>>18)&63]); out.push_back(B64[(v>>12)&63]); out.push_back(B64[(v>>6)&63]); out.push_back(B64[v&63]); i+=3; } if (i < len) { unsigned v = data[i]<<16; int pad = 2; if (i+1 < len) { v |= data[i+1]<<8; pad = 1; } out.push_back(B64[(v>>18)&63]); out.push_back(B64[(v>>12)&63]); out.push_back(pad==1 ? B64[(v>>6)&63] : '='); out.push_back('='); } // wrap at 76 std::string wrapped; wrapped.reserve(out.size()+out.size()/76*2); for (size_t j=0;j& v) { return base64(v.data(), v.size()); } /// @brief Корректная quoted-printable (RFC 2045): без разрывов внутри =XX, /// с кодированием пробелов/табов в конце строки, длина строки ≤ 76. static std::string quoted_printable(const std::string& s) { auto hex2 = [](unsigned char c) { static const char H[] = "0123456789ABCDEF"; std::string r; r.reserve(3); r.push_back('='); r.push_back(H[c >> 4]); r.push_back(H[c & 0xF]); return r; }; std::string out; out.reserve(s.size()*3); int col = 0; auto soft_break = [&](){ out += "=\r\n"; col = 0; }; auto put_plain = [&](char ch){ // для простого символа нужно 1 колонка if (col + 1 > 75) soft_break(); out.push_back(ch); ++col; }; auto put_enc = [&](unsigned char b){ // для =XX нужно 3 колонки if (col + 3 > 75) soft_break(); std::string e = hex2(b); out += e; col += 3; }; for (size_t i = 0; i < s.size(); ++i) { unsigned char c = (unsigned char)s[i]; // нормализуем переводы строк в CRLF if (c == '\r') { if (i + 1 < s.size() && (unsigned char)s[i+1] == '\n') ++i; out += "\r\n"; col = 0; continue; } if (c == '\n') { out += "\r\n"; col = 0; continue; } bool next_is_eol = (i + 1 == s.size()) || (s[i+1] == '\n') || (s[i+1] == '\r'); bool safe = (c == 0x09 || c == 0x20 || (c >= 33 && c <= 60) || (c >= 62 && c <= 126)); // кодируем '=' и все «опасные», а также пробел/таб в конце строки if (c == '=' || !safe || ((c == 0x20 || c == 0x09) && next_is_eol)) { put_enc(c); } else { put_plain((char)c); } } return out; } /// @brief Возвращает дату для заголовка Date (RFC 2822). static std::string rfc2822_date() { // local time with offset time_t t = time(nullptr); struct tm lt{}, gt{}; localtime_r(&t, <); gmtime_r(&t, >); // crude offset time_t local = mktime(<); time_t gm = timegm(>); int offset = (int)difftime(local, gm); // seconds int sign = offset>=0 ? +1 : -1; offset = std::abs(offset); int hh = offset/3600; int mm = (offset%3600)/60; char buf[128]; strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S", <); char out[160]; pg_snprintf(out, sizeof(out), "%s %c%02d%02d", buf, sign>=0?'+':'-', hh, mm); return out; } /// @brief Кодирует строку как RFC 2047 (encoded-word) для заголовков. static std::string rfc2047(const std::string& s) { if (is_ascii(s)) return s; std::string b64 = base64(reinterpret_cast(s.data()), s.size()); return "=?UTF-8?B?" + b64 + "?="; } /// @brief Генерирует Message-ID вида . static std::string gen_message_id(const std::string& host) { std::random_device rd; std::mt19937_64 g(rd()); std::ostringstream o; o << '<' << std::hex << g() << '.' << std::time(nullptr) << '@' << (host.empty()?"localhost":host) << '>'; return o.str(); } /// @brief Грубая проверка адреса email (local@domain). static bool seems_email_addr(const std::string& s) { auto at = s.find('@'); return at!=std::string::npos && at>0 && at+1 lk(g_cfg_mtx); if (!g_override_server.empty()) { // Если в override не указан порт — используем порт из GUC (или 2525 по умолчанию) auto hp = parse_host_port(g_override_server, def_port); c.host = hp.first.empty() ? (base_hp.first.empty() ? "127.0.0.1" : base_hp.first) : hp.first; c.port = hp.second.empty() ? def_port : hp.second; c.helo = !g_override_helo.empty() ? g_override_helo : (c.host.empty() ? "localhost" : c.host); return c; } if (!g_override_helo.empty()) { c.helo = g_override_helo; // host/port зададим ниже } } // 2) Базовая конфигурация из GUC smtp_host_port c.host = base_hp.first.empty() ? "127.0.0.1" : base_hp.first; c.port = def_port.empty() ? "2525" : def_port; if (c.helo.empty()) c.helo = c.host.empty() ? "localhost" : c.host; return c; } /// @brief RAII-обёртка над TCP-сокетом, connect/send/recv, закрытие в деструкторе struct Tcp { int fd{-1}; ~Tcp(){ if(fd>=0) close(fd); } /// @brief Устанавливает таймауты чтения/записи для сокета. void set_timeout(int sec) { timeval tv{}; tv.tv_sec = sec; tv.tv_usec = 0; if (fd>=0) { setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); } } /// @brief Подключается к host:port, возвращает открытый сокет. void connect_to(const std::string& host, const std::string& port) { struct addrinfo hints{}; hints.ai_socktype = SOCK_STREAM; hints.ai_family = AF_UNSPEC; struct addrinfo* res=nullptr; int rc = getaddrinfo(host.c_str(), port.c_str(), &hints, &res); if (rc!=0) ereport(ERROR, (errmsg("UTL_MAIL: DNS resolve failed for \"%s\": %s", host.c_str(), gai_strerror(rc)))); for (auto p=res; p; p=p->ai_next) { int s = socket(p->ai_family, p->ai_socktype, p->ai_protocol); if (s<0) continue; if (::connect(s, p->ai_addr, p->ai_addrlen)==0) { fd=s; break; } close(s); } freeaddrinfo(res); if (fd<0) ereport(ERROR, (errmsg("UTL_MAIL: connect failed to %s:%s", host.c_str(), port.c_str()))); set_timeout(15); } /// @brief Отправляет строку с CRLF. void send_line(const std::string& s) { std::string data = s; if (data.empty() || data.back()!='\n') data += "\r\n"; const char* p = data.c_str(); size_t n = data.size(); while (n) { ssize_t w = ::send(fd, p, n, 0); if (w<=0) ereport(ERROR, (errmsg("UTL_MAIL: send failed"))); p+=w; n-=w; } } /// @brief Считывает строку до CRLF (без декодирования). std::string recv_line_raw() { std::string out; char c; while (true) { ssize_t r = ::recv(fd, &c, 1, 0); if (r<=0) break; out.push_back(c); if (out.size()>=2 && out[out.size()-2]=='\r' && out.back()=='\n') break; } return out; } /// @brief Читает ответ SMTP, возвращает код и текст. std::string recv_reply(int expect_code) { std::string all; std::string line = recv_line_raw(); if (line.empty()) ereport(ERROR, (errmsg("UTL_MAIL: empty SMTP response"))); all += line; if (line.size()<3) ereport(ERROR, (errmsg("UTL_MAIL: malformed SMTP response: %s", line.c_str()))); int code = std::atoi(line.substr(0,3).c_str()); char cont = (line.size()>=4? line[3] : ' '); while (cont=='-') { std::string l2 = recv_line_raw(); if (l2.empty()) break; all += l2; cont = (l2.size()>=4? l2[3] : ' '); } if (code != expect_code) ereport(ERROR, (errmsg("UTL_MAIL: SMTP %d expected, got %d", expect_code, code), errdetail("%s", all.c_str()))); return all; } }; /// @brief Склеивает список адресов в строку заголовка. static std::string join_addrs(const std::vector& v) { std::ostringstream o; for (size_t i=0;i to, cc, bcc; std::string subject; std::string message; std::string mime_type{"text/plain; charset=us-ascii"}; int priority{3}; std::string replyto; std::vector att_data; bool att_inline{true}; std::string att_mime{"application/octet-stream"}; std::string att_filename; }; /// @brief Формирует RFC 5322/MIME-письмо из параметров. static std::string build_message(const MailParams& p, const SmtpConfig& cfg) { std::ostringstream hdr, body; hdr << "From: " << p.sender << "\r\n"; if (!p.to.empty()) hdr << "To: " << join_addrs(p.to) << "\r\n"; if (!p.cc.empty()) hdr << "Cc: " << join_addrs(p.cc) << "\r\n"; if (!p.replyto.empty()) hdr << "Reply-To: " << p.replyto << "\r\n"; hdr << "Subject: " << rfc2047(p.subject) << "\r\n"; hdr << "Date: " << rfc2822_date() << "\r\n"; hdr << "Message-ID: " << gen_message_id(cfg.helo) << "\r\n"; hdr << "MIME-Version: 1.0\r\n"; hdr << "X-Priority: " << std::max(1, std::min(5, p.priority)) << "\r\n"; bool has_att = !p.att_data.empty(); if (!has_att) { std::string mt = p.mime_type.empty()? "text/plain; charset=us-ascii" : p.mime_type; hdr << "Content-Type: " << mt << "\r\n"; hdr << "Content-Transfer-Encoding: quoted-printable\r\n\r\n"; body << quoted_printable(p.message); } else { std::string boundary { TextDatumGetCString(DirectFunctionCall0(utl_mail_gen_boundary)) }; hdr << "Content-Type: multipart/mixed; boundary=\"" << boundary << "\"\r\n\r\n"; // 1: текст body << "--" << boundary << "\r\n"; std::string mt = p.mime_type.empty()? "text/plain; charset=us-ascii" : p.mime_type; body << "Content-Type: " << mt << "\r\n"; body << "Content-Transfer-Encoding: quoted-printable\r\n\r\n"; body << quoted_printable(p.message) << "\r\n"; // 2: вложение body << "--" << boundary << "\r\n"; std::string dispo = p.att_inline ? "inline" : "attachment"; std::string fname = p.att_filename.empty()? "attachment.bin" : p.att_filename; body << "Content-Type: " << (p.att_mime.empty()? "application/octet-stream" : p.att_mime) << "\r\n"; body << "Content-Transfer-Encoding: base64\r\n"; body << "Content-Disposition: " << dispo << "; filename=\"" << fname << "\"\r\n\r\n"; body << base64(p.att_data.data(), p.att_data.size()) << "\r\n"; body << "--" << boundary << "--\r\n"; } return hdr.str() + body.str(); } /// @brief Выполняет SMTP-отправку письма (EHLO..DATA..QUIT). static void smtp_send(const MailParams& p) { if (p.sender.empty()) ereport(ERROR, (errmsg("UTL_MAIL: sender must not be NULL/empty"))); if (p.to.empty() && p.cc.empty() && p.bcc.empty()) ereport(ERROR, (errmsg("UTL_MAIL: recipients (To/Cc/Bcc) must not be empty"))); auto all_rcpt = p.to; all_rcpt.insert(all_rcpt.end(), p.cc.begin(), p.cc.end()); all_rcpt.insert(all_rcpt.end(), p.bcc.begin(), p.bcc.end()); for (auto& a : all_rcpt) if (!seems_email_addr(a)) ereport(ERROR, (errmsg("UTL_MAIL: invalid recipient address: \"%s\"", a.c_str()))); SmtpConfig cfg = read_smtp_config(); std::string message = build_message(p, cfg); std::string data; data.reserve(message.size()+16); { std::istringstream is(message); std::string line; while (std::getline(is, line)) { if (!line.empty() && line.back()=='\r') line.pop_back(); if (!line.empty() && line[0]=='.') data.push_back('.'); data += line; data += "\r\n"; } } Tcp tcp; tcp.connect_to(cfg.host, cfg.port); tcp.recv_reply(220); tcp.send_line("HELO " + cfg.helo); tcp.recv_reply(250); tcp.send_line("MAIL FROM:<" + p.sender + ">"); tcp.recv_reply(250); for (const auto& rcpt : all_rcpt) { tcp.send_line("RCPT TO:<" + rcpt + ">"); // 250 OK / 251 Пользователь не локальный; перешлет std::string resp = tcp.recv_line_raw(); if (resp.size()<3) ereport(ERROR, (errmsg("UTL_MAIL: malformed RCPT response"))); int code = std::atoi(resp.substr(0,3).c_str()); if (!(code==250 || code==251)) { ereport(ERROR, (errmsg("UTL_MAIL: RCPT TO rejected for \"%s\"", rcpt.c_str()), errdetail("%s", resp.c_str()))); } // прочитать дополнительные строки продолжения, если есть if (resp.size()>=4 && resp[3]=='-') { // оставшаясь часть while (true) { std::string cont = tcp.recv_line_raw(); if (cont.empty() || (cont.size()>=4 && cont[3]==' ')) break; } } } tcp.send_line("DATA"); tcp.recv_reply(354); tcp.send_line(data); tcp.send_line("."); tcp.recv_reply(250); tcp.send_line("QUIT"); // игнор ответа } /// @brief Возвращает целое значение или дефолт. static int get_int_or_default(Datum d, bool isnull, int def) { return isnull ? def : DatumGetInt32(d); } /// @brief Конвертирует bytea в вектор байт. static std::vector bytea_to_vec(bytea* b) { std::vector v; if (!b) return v; size_t len = VARSIZE_ANY_EXHDR(b); if (len==0) return v; unsigned char* p = reinterpret_cast(VARDATA_ANY(b)); v.assign(p, p+len); return v; } } // namespace extern "C" { PG_FUNCTION_INFO_V1(utl_mail_send); PG_FUNCTION_INFO_V1(utl_mail_send_attach_raw); PG_FUNCTION_INFO_V1(utl_mail_send_attach_varchar2); PG_FUNCTION_INFO_V1(utl_mail_gen_boundary); PG_FUNCTION_INFO_V1(utl_mail_get_version); /// @brief Версия RUDB пакета UTL_MAIL (Oracle UTL_MAIL пакет) #define RUDB_UTL_MAIL_VERSION "1.0.0" /** * @brief UTL_MAIL.SEND — письмо без вложений. * См. utl_mail.hpp для параметров. */ /* * @qdb_func: utl_mail_send(text, text, text, text, text, text, text, int4, text) * @ora_func: UTL_MAIL.SEND(VARCHAR2, VARCHAR2, VARCHAR2, VARCHAR2, VARCHAR2, VARCHAR2, VARCHAR2, PLS_INTEGER, VARCHAR2) */ Datum utl_mail_send(PG_FUNCTION_ARGS) { text* p_sender = PG_ARGISNULL(0) ? nullptr : PG_GETARG_TEXT_PP(0); text* p_recip = PG_ARGISNULL(1) ? nullptr : PG_GETARG_TEXT_PP(1); text* p_cc = PG_ARGISNULL(2) ? nullptr : PG_GETARG_TEXT_PP(2); text* p_bcc = PG_ARGISNULL(3) ? nullptr : PG_GETARG_TEXT_PP(3); text* p_subject = PG_ARGISNULL(4) ? nullptr : PG_GETARG_TEXT_PP(4); text* p_message = PG_ARGISNULL(5) ? nullptr : PG_GETARG_TEXT_PP(5); text* p_mime = PG_ARGISNULL(6) ? nullptr : PG_GETARG_TEXT_PP(6); int p_priority = get_int_or_default(PG_GETARG_DATUM(7), PG_ARGISNULL(7), 3); text* p_replyto = PG_ARGISNULL(8) ? nullptr : PG_GETARG_TEXT_PP(8); MailParams mp; mp.sender = to_std_string(p_sender); mp.to = split_csv(to_std_string(p_recip)); mp.cc = split_csv(to_std_string(p_cc)); mp.bcc = split_csv(to_std_string(p_bcc)); mp.subject = to_std_string(p_subject); mp.message = to_std_string(p_message); mp.mime_type= to_std_string(p_mime); if (mp.mime_type.empty()) mp.mime_type = "text/plain; charset=us-ascii"; mp.priority = std::max(1, std::min(5, p_priority)); mp.replyto = to_std_string(p_replyto); if (mp.message.empty()) ereport(ERROR, (errmsg("UTL_MAIL: message body must not be NULL/empty"))); smtp_send(mp); PG_RETURN_VOID(); } /** * @brief UTL_MAIL.SEND_ATTACH_RAW — письмо с бинарным вложением. */ /* * @qdb_func: utl_mail_send_attach_raw(text, text, text, text, text, text, text, int4, raw, boolean, text, text, text) * @ora_func: UTL_MAIL.SEND_ATTACH_RAW(VARCHAR2, VARCHAR2, VARCHAR2, VARCHAR2, VARCHAR2, VARCHAR2, VARCHAR2, PLS_INTEGER, RAW, BOOLEAN, VARCHAR2, VARCHAR2, VARCHAR2) */ Datum utl_mail_send_attach_raw(PG_FUNCTION_ARGS) { text* p_sender = PG_ARGISNULL(0) ? nullptr : PG_GETARG_TEXT_PP(0); text* p_recip = PG_ARGISNULL(1) ? nullptr : PG_GETARG_TEXT_PP(1); text* p_cc = PG_ARGISNULL(2) ? nullptr : PG_GETARG_TEXT_PP(2); text* p_bcc = PG_ARGISNULL(3) ? nullptr : PG_GETARG_TEXT_PP(3); text* p_subject = PG_ARGISNULL(4) ? nullptr : PG_GETARG_TEXT_PP(4); text* p_message = PG_ARGISNULL(5) ? nullptr : PG_GETARG_TEXT_PP(5); text* p_mime = PG_ARGISNULL(6) ? nullptr : PG_GETARG_TEXT_PP(6); int p_priority = get_int_or_default(PG_GETARG_DATUM(7), PG_ARGISNULL(7), 3); bytea* p_attach = PG_ARGISNULL(8) ? nullptr : PG_GETARG_BYTEA_PP(8); bool p_inline = PG_ARGISNULL(9) ? true : PG_GETARG_BOOL(9); text* p_att_mime = PG_ARGISNULL(10)? nullptr: PG_GETARG_TEXT_PP(10); text* p_att_name = PG_ARGISNULL(11)? nullptr: PG_GETARG_TEXT_PP(11); text* p_replyto = PG_ARGISNULL(12)? nullptr: PG_GETARG_TEXT_PP(12); MailParams mp; mp.sender = to_std_string(p_sender); mp.to = split_csv(to_std_string(p_recip)); mp.cc = split_csv(to_std_string(p_cc)); mp.bcc = split_csv(to_std_string(p_bcc)); mp.subject = to_std_string(p_subject); mp.message = to_std_string(p_message); mp.mime_type= to_std_string(p_mime); if (mp.mime_type.empty()) mp.mime_type = "text/plain; charset=us-ascii"; mp.priority = std::max(1, std::min(5, p_priority)); mp.replyto = to_std_string(p_replyto); mp.att_data = bytea_to_vec(p_attach); mp.att_inline = p_inline; mp.att_mime = to_std_string(p_att_mime); if (mp.att_mime.empty()) mp.att_mime = "application/octet-stream"; mp.att_filename= to_std_string(p_att_name); if (mp.message.empty()) ereport(ERROR, (errmsg("UTL_MAIL: message body must not be NULL/empty"))); if (mp.att_data.empty()) ereport(ERROR, (errmsg("UTL_MAIL: attachment (RAW) must not be NULL/empty"))); smtp_send(mp); PG_RETURN_VOID(); } /** * @brief UTL_MAIL.SEND_ATTACH_VARCHAR2 — письмо с текстовым вложением. */ /* * @qdb_func: utl_mail_send_attach_varchar2(text, text, text, text, text, text, text, int4, text, boolean, text, text, text) * @ora_func: UTL_MAIL.SEND_ATTACH_VARCHAR2(VARCHAR2, VARCHAR2, VARCHAR2, VARCHAR2, VARCHAR2, VARCHAR2, VARCHAR2, PLS_INTEGER, VARCHAR2, BOOLEAN, VARCHAR2, VARCHAR2, VARCHAR2) */ Datum utl_mail_send_attach_varchar2(PG_FUNCTION_ARGS) { text* p_sender = PG_ARGISNULL(0) ? nullptr : PG_GETARG_TEXT_PP(0); text* p_recip = PG_ARGISNULL(1) ? nullptr : PG_GETARG_TEXT_PP(1); text* p_cc = PG_ARGISNULL(2) ? nullptr : PG_GETARG_TEXT_PP(2); text* p_bcc = PG_ARGISNULL(3) ? nullptr : PG_GETARG_TEXT_PP(3); text* p_subject = PG_ARGISNULL(4) ? nullptr : PG_GETARG_TEXT_PP(4); text* p_message = PG_ARGISNULL(5) ? nullptr : PG_GETARG_TEXT_PP(5); text* p_mime = PG_ARGISNULL(6) ? nullptr : PG_GETARG_TEXT_PP(6); int p_priority = get_int_or_default(PG_GETARG_DATUM(7), PG_ARGISNULL(7), 3); text* p_att_text = PG_ARGISNULL(8) ? nullptr : PG_GETARG_TEXT_PP(8); bool p_inline = PG_ARGISNULL(9) ? true : PG_GETARG_BOOL(9); text* p_att_mime = PG_ARGISNULL(10)? nullptr: PG_GETARG_TEXT_PP(10); text* p_att_name = PG_ARGISNULL(11)? nullptr: PG_GETARG_TEXT_PP(11); text* p_replyto = PG_ARGISNULL(12)? nullptr: PG_GETARG_TEXT_PP(12); MailParams mp; mp.sender = to_std_string(p_sender); mp.to = split_csv(to_std_string(p_recip)); mp.cc = split_csv(to_std_string(p_cc)); mp.bcc = split_csv(to_std_string(p_bcc)); mp.subject = to_std_string(p_subject); mp.message = to_std_string(p_message); mp.mime_type= to_std_string(p_mime); if (mp.mime_type.empty()) mp.mime_type = "text/plain; charset=us-ascii"; mp.priority = std::max(1, std::min(5, p_priority)); mp.replyto = to_std_string(p_replyto); std::string att = to_std_string(p_att_text); if (!att.empty()) mp.att_data.assign(att.begin(), att.end()); mp.att_inline = p_inline; mp.att_mime = to_std_string(p_att_mime); if (mp.att_mime.empty()) mp.att_mime = "text/plain; charset=us-ascii"; mp.att_filename= to_std_string(p_att_name); if (mp.att_filename.empty()) mp.att_filename = "attachment.txt"; if (mp.message.empty()) ereport(ERROR, (errmsg("UTL_MAIL: message body must not be NULL/empty"))); if (mp.att_data.empty()) ereport(ERROR, (errmsg("UTL_MAIL: attachment (VARCHAR2) must not be NULL/empty"))); smtp_send(mp); PG_RETURN_VOID(); } Datum utl_mail_gen_boundary(PG_FUNCTION_ARGS) { std::random_device rd; std::mt19937_64 g(rd()); std::ostringstream o; o << "----=_qdb_" << std::hex << g(); PG_RETURN_TEXT_P(cstring_to_text(o.str().c_str())); } /// @brief Возвращает версию RUDB пакета UTL_MAIL (Oracle UTL_MAIL пакет) Datum utl_mail_get_version(PG_FUNCTION_ARGS) { PG_RETURN_TEXT_P(cstring_to_text(RUDB_UTL_MAIL_VERSION)); } } // extern "C"