Saltar al contenido principal
Versión: 20 R5 BETA

SMTPTransporter

The SMTPTransporter class allows you to configure SMTP connections and send emails through SMTP transporter objects.

Objeto SMTP Transporter

SMTP Transporter objects are instantiated with the SMTP New transporter command. Ofrecen las siguientes propiedades y funciones:

.acceptUnsecureConnection : Boolean    True if 4D is allowed to establish an unencrypted connection
.authenticationMode : Text    the authentication mode used to open the session on the mail server
.bodyCharset : Text     the charset and encoding used for the body part of the email
.checkConnection() : Object     checks the connection using information stored in the transporter object
.connectionTimeOut : Integer    the maximum wait time (in seconds) allowed to establish a connection to the server
.headerCharset : Text     the charset and encoding used for the email header
.host : Text    the name or the IP address of the host server
.keepAlive : Boolean    True if the SMTP connection must be kept alive until the transporter object is destroyed
.logFile : Text    the path of the extended log file defined (if any) for the mail connection
.port : Integer     the port number used for mail transactions
.send( mail : Object ) : Object    sends the mail object to the SMTP server defined in the transporter object and returns a status object
.sendTimeOut : Integer     the maximum wait time (in seconds) of a call to .send( ) before a timeout occurs
.user : Text     the user name used for authentication on the mail server

SMTP New transporter

Historia
LanzamientoModificaciones
18Nueva propiedad logFile
17 R5Nuevas propiedades bodyCharset y headerCharset
17 R4Añadidos

SMTP New transporter( server : Object ) : 4D.SMTPTransporter

ParámetrosTipoDescripción
serverObject->Información del servidor de correo
Result4D.SMTPTransporter<-SMTP transporter object

Descripción

The SMTP New transporter command configures a new SMTP connection according to the server parameter and returns a new SMTP transporter object. El objeto transportador devuelto se utilizará normalmente para el envío de correos electrónicos.

Este comando no abre ninguna conexión con el servidor SMTP. The SMTP connection is actually opened when the .send() function is executed.

La conexión SMTP se cierra automáticamente:

  • when the transporter object is destroyed if the keepAlive property is true (default),
  • after each .send( ) function execution if the keepAlive property is set to false.

In the server parameter, pass an object containing the following properties:

serverValor por defecto (si se omite)
.acceptUnsecureConnection : Boolean&nbsp;&nbsp;&nbsp;&nbsp;True if 4D is allowed to establish an unencrypted connectionFalse
.accessTokenOAuth2: Text
.accessTokenOAuth2: Object
Text string or token object representing OAuth2 authorization credentials. Used only with OAUTH2 authenticationMode. If accessTokenOAuth2 is used but authenticationMode is omitted, the OAuth 2 protocol is used (if allowed by the server). Not returned in SMTP transporter object.
ninguno
.authenticationMode : Text&nbsp;&nbsp;&nbsp;&nbsp;the authentication mode used to open the session on the mail serverse utiliza el modo de autenticación más seguro soportado por el servidor
.bodyCharset : Text&nbsp;&nbsp;&nbsp;&nbsp; the charset and encoding used for the body part of the emailmail mode UTF8 (US-ASCII_UTF8_QP)
.connectionTimeOut : Integer&nbsp;&nbsp;&nbsp;&nbsp;the maximum wait time (in seconds) allowed to establish a connection to the server30
.headerCharset : Text&nbsp;&nbsp;&nbsp;&nbsp; the charset and encoding used for the email headermail mode UTF8 (US-ASCII_UTF8_QP)
.host : Text&nbsp;&nbsp;&nbsp;&nbsp;the name or the IP address of the host serverobligatorio
.keepAlive : Boolean&nbsp;&nbsp;&nbsp;&nbsp;True if the SMTP connection must be kept alive until the transporter object is destroyedTrue
.logFile : Text&nbsp;&nbsp;&nbsp;&nbsp;the path of the extended log file defined (if any) for the mail connectionninguno
password : Text
User password for authentication on the server. Not returned in SMTP transporter object.
ninguno
.port : Integer&nbsp;&nbsp;&nbsp;&nbsp; the port number used for mail transactions587
.sendTimeOut : Integer&nbsp;&nbsp;&nbsp;&nbsp; the maximum wait time (in seconds) of a call to .send( ) before a timeout occurs100
.user : Text&nbsp;&nbsp;&nbsp;&nbsp; the user name used for authentication on the mail serverninguno

Result

The function returns a SMTP transporter object. All returned properties are read-only.

Ejemplo

 $server:=New object
$server.host:="smtp.gmail.com" //Mandatory
$server.port:=465
$server.user:="4D@gmail.com"
$server.password:="XXXX"
$server.logFile:="LogTest.txt" //Extended log to save in the Logs folder

var $transporter : 4D.SMTPTransporter
$transporter:=SMTP New transporter($server)

$email:=New object
$email.subject:="my first mail "
$email.from:="4d@gmail.com"
$email.to:="4d@4d.com;test@4d.com"
$email.textBody:="Hello World"
$email.htmlBody:="<h1>Hello World</h1><h4>'Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...'</h4>\
<p>There are many variations of passages of Lorem Ipsum available."\
+"The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.</p>"

$status:=$transporter.send($email)
If(Not($status.success))
ALERT("An error occurred sending the mail: "+$status.message)
End if

4D.SMTPTransporter.new()

4D.SMTPTransporter.new( server : Object ) : 4D.SMTPTransporter

ParámetrosTipoDescripción
serverObject->Información del servidor de correo
Result4D.SMTPTransporter<-SMTP transporter object

Descripción

The 4D.SMTPTransporter.new() function creates and returns a new object of the 4D.SMTPTransporter type. It is identical to the SMTP New transporter command (shortcut).

.acceptUnsecureConnection

Historia
LanzamientoModificaciones
17 R4Añadidos

.acceptUnsecureConnection : Boolean

Descripción

The .acceptUnsecureConnection property contains True if 4D is allowed to establish an unencrypted connection when encrypted connection is not possible.

It contains False if unencrypted connections are unallowed, in which case an error in returned when encrypted connection is not possible.

Los puertos seguros disponibles son:

  • SMTP

    • 465: SMTPS
    • 587 o 25: SMTP con actualización STARTTLS si lo soporta el servidor.
  • IMAP

    • 143: Puerto IMAP no encriptado
    • 993: IMAP con actualización STARTTLS si lo soporta el servidor
  • POP3

    • 110: Puerto POP3 no encriptado
    • 995: POP3 con actualización STARTTLS si lo soporta el servidor.

.authenticationMode

Historia
LanzamientoModificaciones
17 R4Añadidos

.authenticationMode : Text

Descripción

The .authenticationMode property contains the authentication mode used to open the session on the mail server.

Por defecto, se utiliza el modo más seguro soportado por el servidor.

Los valores posibles son:

ValorConstantesComentario
CRAM-MD5SMTP authentication CRAM MD5Autenticación utilizando el protocolo CRAM-MD5
LOGINSMTP authentication loginAutenticación utilizando el protocolo LOGIN
OAUTH2SMTP authentication OAUTH2Autenticación utilizando el protocolo OAuth2
PLAINSMTP authentication plainAutenticación utilizando el protocolo PLAIN

.bodyCharset

Historia
LanzamientoModificaciones
18Soporte de UTF8 base64
17 R5Añadidos

.bodyCharset : Text

Descripción

The .bodyCharset property contains the charset and encoding used for the body part of the email.

Valores posibles:

ConstanteValorComentario
mail mode ISO2022JPUS-ASCII_ISO-2022-JP_UTF8_QP
  • headerCharset: US-ASCII if possible, Japanese (ISO-2022-JP) & Quoted-printable if possible, otherwise UTF-8 & Quoted-printable
  • bodyCharset: US-ASCII if possible, Japanese (ISO-2022-JP) & 7-bit if possible, otherwise UTF-8 & Quoted-printable
mail mode ISO88591ISO-8859-1
  • headerCharset: ISO-8859-1 & Quoted-printable
  • bodyCharset: ISO-8859-1 & 8-bit
mail mode UTF8US-ASCII_UTF8_QPheaderCharset & bodyCharset: US-ASCII if possible, otherwise UTF-8 & Quoted-printable (default value)
mail mode UTF8 in base64US-ASCII_UTF8_B64headerCharset & bodyCharset: US-ASCII if possible, otherwise UTF-8 & base64

.checkConnection()

Historia
LanzamientoModificaciones
17 R4Añadidos

.checkConnection() : Object

ParámetrosTipoDescripción
ResultObject<-Estado de la conexión del objeto transportador

Descripción

The .checkConnection() function checks the connection using information stored in the transporter object, recreates the connection if necessary, and returns the status. Esta función permite verificar que los valores proporcionados por el usuario son válidos y coherentes.

Objeto devuelto

La función envía una solicitud al servidor de correo y devuelve un objeto que describe el estado del correo. Este objeto puede contener las siguientes propiedades:

PropiedadTipoDescripción
successbooleanTrue si la verificación es exitosa, False en caso contrario
statusnumber(sólo SMTP) Código de estado devuelto por el servidor de correo (0 en caso de un problema no relacionado con el procesamiento del correo)
statusTexttextMensaje de estado devuelto por el servidor de correo, o último error devuelto en la pila de errores de 4D
errorscollectionPila de errores 4D (no se devuelve si se recibe una respuesta del servidor de correo)
[ ].errCodenumberCódigo de error 4D
[ ].messagetextDescripción del error 4D
[ ].componentSignaturetextFirma del componente interno que ha devuelto el error

For information about SMTP status codes, please refer to this page.

Ejemplo

 var $pw : Text
var $options : Object
var $transporter : 4D.SMTPTransporter
$options:=New object

$pw:=Request("Please enter your password:")
$options.host:="smtp.gmail.com"

$options.user:="test@gmail.com"
$options.password:=$pw

$transporter:=SMTP New transporter($options)

$status:=$transporter.checkConnection()
If($status.success=True)
ALERT("SMTP connection check successful!")
Else
ALERT("Error # "+String($status.status)+", "+$status.statusText)
End if

.connectionTimeOut

Historia
LanzamientoModificaciones
17 R5Añadidos

.connectionTimeOut : Integer

Descripción

The .connectionTimeOut property contains the maximum wait time (in seconds) allowed to establish a connection to the server. By default, if the property has not been set in the server object (used to create the transporter object with SMTP New transporter, POP3 New transporter, or IMAP New transporter), the value is 30.

.headerCharset

Historia
LanzamientoModificaciones
17 R5Añadidos

.headerCharset : Text

Descripción

The .headerCharset property contains the charset and encoding used for the email header. El encabezado incluye las siguientes partes del correo electrónico:

  • asunto,
  • attachment filename(s),
  • email name.

Valores posibles:

ConstanteValorComentario
mail mode ISO2022JPUS-ASCII_ISO-2022-JP_UTF8_QP
  • headerCharset: US-ASCII if possible, Japanese (ISO-2022-JP) & Quoted-printable if possible, otherwise UTF-8 & Quoted-printable
  • bodyCharset: US-ASCII if possible, Japanese (ISO-2022-JP) & 7-bit if possible, otherwise UTF-8 & Quoted-printable
mail mode ISO88591ISO-8859-1
  • headerCharset: ISO-8859-1 & Quoted-printable
  • bodyCharset: ISO-8859-1 & 8-bit
mail mode UTF8US-ASCII_UTF8_QPheaderCharset & bodyCharset: US-ASCII if possible, otherwise UTF-8 & Quoted-printable (default value)
mail mode UTF8 in base64US-ASCII_UTF8_B64headerCharset & bodyCharset: US-ASCII if possible, otherwise UTF-8 & base64

.host

Historia
LanzamientoModificaciones
17 R5Añadidos

.host : Text

Descripción

The .host property contains the name or the IP address of the host server. Se utiliza para las transacciones de correo (SMTP, POP3, IMAP).

.keepAlive

Historia
LanzamientoModificaciones
17 R4Añadidos

.keepAlive : Boolean

Descripción

The .keepAlive property contains True if the SMTP connection must be kept alive until the transporter object is destroyed, and False otherwise. By default, if the keepAlive property has not been set in the server object (used to create the transporter object with SMTP New transporter), it is True.

La conexión SMTP se cierra automáticamente:

  • when the transporter object is destroyed if the .keepAlive property is true,
  • after each .send( ) function execution if the .keepAlive property is set to false.

.logFile

Historia
LanzamientoModificaciones
17 R5Añadidos

.logFile : Text

Descripción

The .logFile property contains the path of the extended log file defined (if any) for the mail connection. Puede ser relativo (a la carpeta actual Logs) o absoluto.

Unlike regular log files (enabled via the SET DATABASE PARAMETER command), extended log files store MIME contents of all sent mails and do not have any size limit. Para más información sobre los archivos de registro extendidos, consulte:

.port

Historia
LanzamientoModificaciones
17 R4Añadidos

.port : Integer

Descripción

The .port property contains the port number used for mail transactions. By default, if the port property has not been set in the server object (used to create the transporter object with SMTP New transporter, POP3 New transporter, IMAP New transporter), the port used is:

  • SMTP - 587
  • POP3 - 995
  • IMAP - 993

.send()

Historia
LanzamientoModificaciones
17 R5Soporte de contenidos Mime
17 R4Añadidos

.send( mail : Object ) : Object

ParámetrosTipoDescripción
mailObject->Email to send
ResultObject<-Estado SMTP

Descripción

The .send() function sends the mail object to the SMTP server defined in the transporter object and returns a status object.

The transporter object must have already been created using the SMTP New transporter command.

El método crea la conexión SMTP si no está ya activa. If the .keepAlive property of the transporter object is false, the SMTP connection is automatically closed after the execution of .send(), otherwise it stays alive until the transporter object is destroyed. For more information, please refer to the SMTP New transporter command description.

In mail, pass a valid Email object to send. Las propiedades origen (de dónde viene el correo electrónico) y destino (uno o varios destinatarios) deben incluirse, el resto de propiedades son opcionales.

Objeto devuelto

La función devuelve un objeto que describe el estado SMTP de la operación. Este objeto puede contener las siguientes propiedades:

PropiedadTipoDescripción
successbooleanTrue si el envío tiene éxito, false en caso contrario
statusnumberCódigo de estado devuelto por el servidor SMTP (0 en caso de un problema no relacionado con el procesamiento del correo)
statusTexttextMensaje de estado devuelto por el servidor SMTP

In case of an issue unrelated to the SMTP processing (e.g. a mandatory property is missing in mail), 4D generates an error that you can intercept using a method installed by the ON ERR CALL command. Use the GET LAST ERROR STACK command for information about the error.

En este caso, el objeto estado resultante contiene los siguientes valores:

PropiedadValor
successFalse
status0
statusText"Failed to send email"

.sendTimeOut

Historia
LanzamientoModificaciones
17 R4Añadidos

.sendTimeOut : Integer

Descripción

The .sendTimeOut property contains the maximum wait time (in seconds) of a call to .send( ) before a timeout occurs. By default, if the .sendTimeOut property has not been set in the server object, the value 100 is used.

.user

Historia
LanzamientoModificaciones
17 R4Añadidos

.user : Text

Descripción

The .user property contains the user name used for authentication on the mail server.