G.10. utl_mail — управление электронными письмами #
utl_mail — это расширение Postgres Pro, предназначенное для управления электронными письмами, включая управление часто используемыми возможностями электронной почты, такими как вложение, копия и скрытая копия. Функциональность, предоставляемая этим модулем, во многом пересекается с функциональностью пакета UTL_MAIL в Oracle, но может отправлять больший объём данных, поскольку в Postgres Pro для отправки используется тип text, способный хранить до 1 ГБ данных.
G.10.1. Установка #
Расширение utl_mail поставляется вместе с Postgres Pro Enterprise в отдельном пакете pgpro-orautl-ent-16 (подробные инструкции по установке приведены в Главе 17). Чтобы включить utl_mail, создайте расширение с помощью следующего запроса:
CREATE EXTENSION utl_mail;
G.10.2. Функции utl_mail #
Расширение utl_mail предоставляет функции для управления электронными письмами. Обратите внимание, что некоторые параметры приведённых ниже функций, а именно host, port, timeout, username и password необходимы для установления соединения с SMTP-сервером и аутентификации.
-
send(#hosttext,portint,timeoutint,usernametext,passwordtext,sendertext,recipientstext,messagetext,cctextdefault null,bcctextdefault null,subjecttextdefault null,mime_typetextdefault 'text/plain; charset=UTF-8',priorityintdefault 3,replytotextdefault null,starttlsbooldefault true) Упаковывает электронное письмо в соответствующий формат и отправляет это письмо на указанный SMTP-сервер.
-
send_attach_bytea(#hosttext,portint,timeoutint,usernametext,passwordtext,sendertext,recipientstext,attachmentbytea,messagetext,cctextdefault null,bcctextdefault null,subjecttextdefault null,mime_typetextdefault 'text/plain; charset=UTF-8',priorityintdefault 3,att_inlinebooldefault true,att_mime_typetextdefault 'application/octet-stream',att_filenametextdefault null,replytotextdefault null,starttlsbooldefault true) Упаковывает электронное письмо, содержащее вложение типа
bytea, в соответствующий формат и отправляет это письмо на указанный SMTP-сервер.В параметре
attachmentуказывается вложение типаbytea. Параметрatt_inlineуказывает, можно ли просматривать вложение в теле письма, значение по умолчанию — true. Параметрatt_mime_type— это mime-тип вложения, по умолчанию —application/octet. Параметрatt_filename— это строка с именем файла вложения, по умолчанию — null.-
send_attach_text(#hosttext,portint,timeoutint,usernametext,passwordtext,sendertext,recipientstext,attachmenttext,messagetext,cctextdefault null,bcctextdefault null,subjecttextdefault null,mime_typetextdefault 'text/plain; charset=UTF-8',priorityintdefault 3,att_inlinebooldefault true,att_mime_typetextdefault 'text/plain; charset=UTF-8',att_filenametextdefault null,replytotextdefault null,starttlsbooldefault true) Упаковывает электронное письмо, содержащее вложение типа
text, в соответствующий формат и отправляет это письмо на указанный SMTP-сервер.В параметре
attachmentуказывается вложение типаtext. Параметрatt_inlineуказывает, можно ли просматривать вложение в теле письма, значение по умолчанию — true. Параметрatt_mime_type— это mime-тип вложения, по умолчанию —application/octet. Параметрatt_filename— это строка с именем файла вложения, по умолчанию — null.
G.10.3. Пример #
В следующем примере показана отправка электронного письма с вложением с помощью расширения utl_mail.
CREATE TABLE pictures (pic bytea);
INSERT INTO pictures (pic) values (pg_read_binary_file('/home/postgres/slon.jpg'));
DO $$
DECLARE
picture bytea;
BEGIN
SELECT * INTO picture FROM pictures LIMIT 1;
CALL utl_mail.send_attach_bytea
(
host => 'smtp.example.com',
port => 25,
timeout => 10,
username => 'username@example.com',
password => <password>,
sender => 'Sender <sender@example.com>',
recipients => 'Recipient <recipient@example.com>',
message => 'Letter from pgpro_utl_mail!',
attachment => picture,
subject => 'utl_mail letter with picture',
att_filename => 'slon.jpg',
priority => 1
);
END$$;
G.10. utl_mail — manage emails #
utl_mail is a Postgres Pro extension designed for managing emails, which includes commonly used email features, such as attachments, CC, and BCC. The functionality provided by this module overlaps substantially with the functionality of Oracle's UTL_MAIL package but larger amount of data can be sent as in Postgres Pro the text type is used for sending data, which can store up to 1GB.
G.10.1. Installation #
The utl_mail extension is provided with Postgres Pro Enterprise in a separate pre-built package pgpro-orautl-ent-16 (for the detailed installation instructions, see Chapter 17). To enable utl_mail, create the extension using the following query:
CREATE EXTENSION utl_mail;
G.10.2. utl_mail Functions #
utl_mail provides functions for email management. Note that some of the parameters within functions below, namely host, port, timeout, username, and password, are required to establish connection with the SMTP server and authentication.
-
send(#hosttext,portint,timeoutint,usernametext,passwordtext,sendertext,recipientstext,messagetext,cctextdefault null,bcctextdefault null,subjecttextdefault null,mime_typetextdefault 'text/plain; charset=UTF-8',priorityintdefault 3,replytotextdefault null,starttlsbooldefault true) Packages an email into the appropriate format and sends the email to the specified SMTP server.
-
send_attach_bytea(#hosttext,portint,timeoutint,usernametext,passwordtext,sendertext,recipientstext,attachmentbytea,messagetext,cctextdefault null,bcctextdefault null,subjecttextdefault null,mime_typetextdefault 'text/plain; charset=UTF-8',priorityintdefault 3,att_inlinebooldefault true,att_mime_typetextdefault 'application/octet-stream',att_filenametextdefault null,replytotextdefault null,starttlsbooldefault true) Packages an email containing a
byteaattachment into the appropriate format and sends the email to the specified SMTP server.The
attachmentspecifies thebyteaattachment. Theatt_inlinespecifies whether the attachment is viewable within the email body, default is true. Theatt_mime_typeis the mime type of the attachment, default isapplication/octet. Theatt_filenameis the string specifying the filename of the attachment, default is null.-
send_attach_text(#hosttext,portint,timeoutint,usernametext,passwordtext,sendertext,recipientstext,attachmenttext,messagetext,cctextdefault null,bcctextdefault null,subjecttextdefault null,mime_typetextdefault 'text/plain; charset=UTF-8',priorityintdefault 3,att_inlinebooldefault true,att_mime_typetextdefault 'text/plain; charset=UTF-8',att_filenametextdefault null,replytotextdefault null,starttlsbooldefault true) Packages an email containing a
textattachment into the appropriate format and sends the email to the specified SMTP server.The
attachmentspecifies thetextattachment. Theatt_inlinespecifies whether the attachment is viewable within the email body, default is true. Theatt_mime_typeis the mime type of the attachment, default isapplication/octet. Theatt_filenameis the string specifying the filename of the attachment, default is null.
G.10.3. Example #
The following example demonstrates sending an email with an attachment using utl_mail.
CREATE TABLE pictures (pic bytea);
INSERT INTO pictures (pic) values (pg_read_binary_file('/home/postgres/slon.jpg'));
DO $$
DECLARE
picture bytea;
BEGIN
SELECT * INTO picture FROM pictures LIMIT 1;
CALL utl_mail.send_attach_bytea
(
host => 'smtp.example.com',
port => 25,
timeout => 10,
username => 'username@example.com',
password => <password>,
sender => 'Sender <sender@example.com>',
recipients => 'Recipient <recipient@example.com>',
message => 'Letter from pgpro_utl_mail!',
attachment => picture,
subject => 'utl_mail letter with picture',
att_filename => 'slon.jpg',
priority => 1
);
END$$;