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(host text, port int, timeout int, username text, password text, sender text, recipients text, message text, cc text default null, bcc text default null, subject text default null, mime_type text default 'text/plain; charset=UTF-8', priority int default 3, replyto text default null, starttls bool default true) #

Упаковывает электронное письмо в соответствующий формат и отправляет это письмо на указанный SMTP-сервер.

send_attach_bytea(host text, port int, timeout int, username text, password text, sender text, recipients text, attachment bytea, message text, cc text default null, bcc text default null, subject text default null, mime_type text default 'text/plain; charset=UTF-8', priority int default 3, att_inline bool default true, att_mime_type text default 'application/octet-stream', att_filename text default null, replyto text default null, starttls bool default true) #

Упаковывает электронное письмо, содержащее вложение типа bytea, в соответствующий формат и отправляет это письмо на указанный SMTP-сервер.

В параметре attachment указывается вложение типа bytea. Параметр att_inline указывает, можно ли просматривать вложение в теле письма, значение по умолчанию — true. Параметр att_mime_type — это mime-тип вложения, по умолчанию — application/octet. Параметр att_filename — это строка с именем файла вложения, по умолчанию — null.

send_attach_text(host text, port int, timeout int, username text, password text, sender text, recipients text, attachment text, message text, cc text default null, bcc text default null, subject text default null, mime_type text default 'text/plain; charset=UTF-8', priority int default 3, att_inline bool default true, att_mime_type text default 'text/plain; charset=UTF-8', att_filename text default null, replyto text default null, starttls bool default 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(host text, port int, timeout int, username text, password text, sender text, recipients text, message text, cc text default null, bcc text default null, subject text default null, mime_type text default 'text/plain; charset=UTF-8', priority int default 3, replyto text default null, starttls bool default true) #

Packages an email into the appropriate format and sends the email to the specified SMTP server.

send_attach_bytea(host text, port int, timeout int, username text, password text, sender text, recipients text, attachment bytea, message text, cc text default null, bcc text default null, subject text default null, mime_type text default 'text/plain; charset=UTF-8', priority int default 3, att_inline bool default true, att_mime_type text default 'application/octet-stream', att_filename text default null, replyto text default null, starttls bool default true) #

Packages an email containing a bytea attachment into the appropriate format and sends the email to the specified SMTP server.

The attachment specifies the bytea attachment. The att_inline specifies whether the attachment is viewable within the email body, default is true. The att_mime_type is the mime type of the attachment, default is application/octet. The att_filename is the string specifying the filename of the attachment, default is null.

send_attach_text(host text, port int, timeout int, username text, password text, sender text, recipients text, attachment text, message text, cc text default null, bcc text default null, subject text default null, mime_type text default 'text/plain; charset=UTF-8', priority int default 3, att_inline bool default true, att_mime_type text default 'text/plain; charset=UTF-8', att_filename text default null, replyto text default null, starttls bool default true) #

Packages an email containing a text attachment into the appropriate format and sends the email to the specified SMTP server.

The attachment specifies the text attachment. The att_inline specifies whether the attachment is viewable within the email body, default is true. The att_mime_type is the mime type of the attachment, default is application/octet. The att_filename is 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$$;

FAQ