Saltar al contenido principal
Versión: 20 R5 BETA

IMAPTransporter

The IMAPTransporter class allows you to retrieve messages from a IMAP email server.

Objeto IMAP Transporter

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

.acceptUnsecureConnection : Boolean    True if 4D is allowed to establish an unencrypted connection
.addFlags( msgIDs : Collection ; keywords : Object ) : Object
.addFlags( msgIDs : Text ; keywords : Object ) : Object
.addFlags( msgIDs : Longint ; keywords : Object ) : Object
    adds flags to the msgIDs for the specified keywords
.append( mailObj : Object ; destinationBox : Text ; options : Object ) : Object    appends a mailObj to the destinationBox
.authenticationMode : Text    the authentication mode used to open the session on the mail server
.checkConnection() : Object     checks the connection using information stored in the transporter object
.checkConnectionDelay : Integer    the maximum time (in seconds) allowed prior to checking the connection to the server
.connectionTimeOut : Integer    the maximum wait time (in seconds) allowed to establish a connection to the server
.copy( msgsIDs : Collection ; destinationBox : Text ) : Object
.copy( allMsgs : Integer ; destinationBox : Text ) : Object
    copies the messages defined by msgsIDs or allMsgs to the destinationBox on the IMAP server
.createBox( name : Text ) : Object    creates a mailbox with the given name
.delete( msgsIDs : Collection ) : Object
.delete( allMsgs : Integer ) : Object
    sets the "deleted" flag for the messages defined in msgsIDs or allMsgs
.deleteBox( name : Text ) : Object    permanently removes the mailbox with the given name from the IMAP server
.expunge() : Object    removes all messages with the "deleted" flag from the IMAP mail server.
.getBoxInfo( { name : Text }) : Object    returns a boxInfo object corresponding to the current maibox, or the mailbox name
.getBoxList( { parameters : Object } ) : Collection    returns a collection of mailboxes describing all of the available mailboxes
.getDelimiter() : Text    returns the character used to delimit levels of hierarchy in the mailbox name
.getMail( msgNumber: Integer { ; options : Object } ) : Object
.getMail( msgID: Text { ; options : Object } ) : Object
    returns the Email object corresponding to the msgNumber or msgID in the mailbox designated by the IMAP_transporter
.getMails( ids : Collection { ; options : Object } ) : Object
.getMails( startMsg : Integer ; endMsg : Integer { ; options : Object } ) : Object
    returns an object containing a collection of Email objects
.getMIMEAsBlob( msgNumber : Integer { ; updateSeen : Boolean } ) : Blob
.getMIMEAsBlob( msgID : Text { ; updateSeen : Boolean } ) : Blob
    returns a BLOB containing the MIME contents for the message corresponding to the msgNumber or msgID in the mailbox designated by the IMAP_transporter
.host : Text    the name or the IP address of the host server
.logFile : Text    the path of the extended log file defined (if any) for the mail connection
.move( msgsIDs : Collection ; destinationBox : Text ) : Object
.move( allMsgs : Integer ; destinationBox : Text ) : Object
    moves the messages defined by msgsIDs or allMsgs to the destinationBox on the IMAP server
.numToID( startMsg : Integer ; endMsg : Integer ) : Collection    converts the sequence numbers to IMAP unique IDs for the messages in the sequential range designated by startMsg and endMsg
.removeFlags( msgIDs : Collection ; keywords : Object ) : Object
.removeFlags( msgIDs : Text ; keywords : Object ) : Object
.removeFlags( msgIDs : Longint ; keywords : Object ) : Object
    removes flags from the msgIDs for the specified keywords
.renameBox( currentName : Text ; newName : Text ) : Object    changes the name of a mailbox on the IMAP server
.port : Integer     the port number used for mail transactions
.searchMails( searchCriteria : Text ) : Collection    searches for messages that match the given searchCriteria in the current mailbox
.selectBox( name : Text { ; state : Integer } ) : Object    selects the name mailbox as the current mailbox
.subscribe( name : Text ) : Object    allows adding or removing of the specified mailbox to/from the IMAP server’s set of “subscribed” mailboxes
.unsubscribe( name : Text ) : Object    removes a mailbox from a set of subscribed mailboxes
.user : Text     the user name used for authentication on the mail server

IMAP New transporter

Historia
LanzamientoModificaciones
18 R4Añadidos

IMAP New transporter( server : Object ) : 4D.IMAPTransporter

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

Descripción

The IMAP New transporter command configures a new IMAP connection according to the server parameter and returns a new transporter object. El objeto transportador devuelto se utilizará normalmente para recibir correos electrónicos.

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 IMAP 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
.checkConnectionDelay : Integer&nbsp;&nbsp;&nbsp;&nbsp;the maximum time (in seconds) allowed prior to checking the connection to the server300
.connectionTimeOut : Integer&nbsp;&nbsp;&nbsp;&nbsp;the maximum wait time (in seconds) allowed to establish a connection to the server30
.host : Text&nbsp;&nbsp;&nbsp;&nbsp;the name or the IP address of the host serverobligatorio
.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 IMAP transporter object.
ninguno
.port : Integer&nbsp;&nbsp;&nbsp;&nbsp; the port number used for mail transactions993
.user : Text&nbsp;&nbsp;&nbsp;&nbsp; the user name used for authentication on the mail serverninguno

Warning: Make sure the defined timeout is lower than the server timeout, otherwise the client timeout will be useless.

Result

The function returns an IMAP transporter object. All returned properties are read-only.

La conexión IMAP se cierra automáticamente cuando se destruye el objeto transportador.

Ejemplo

$server:=New object
$server.host:="imap.gmail.com" //Obligatorio
$server.port:=993
$server.user:="4d@gmail.com"
$server.password:="XXXXXXXX"
$server.logFile:="LogTest.txt" //log a guardar en la carpeta Logs

var $transporter : 4D.IMAPTransporter
$transporter:=IMAP New transporter($server)

$status:=$transporter.checkConnection()
If(Not($status.success))
ALERT("An error occurred: "+$status.statusText)
End if

4D.IMAPTransporter.new()

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

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

Descripción

The 4D.IMAPTransporter.new() function creates and returns a new object of the 4D.IMAPTransporter type. It is identical to the IMAP 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.

.addFlags()

Historia
LanzamientoModificaciones
20Soporta palabras claves personalizadas
18 R6Añadidos

.addFlags( msgIDs : Collection ; keywords : Object ) : Object
.addFlags( msgIDs : Text ; keywords : Object ) : Object
.addFlags( msgIDs : Longint ; keywords : Object ) : Object

ParámetrosTipoDescripción
msgIDsCollection->Colección de cadenas: identificadores únicos de mensajes (texto)
Texto: ID único de un mensaje
Longint (IMAP all): todos los mensajes del buzón seleccionado
keywordsObject->Banderas de palabras claves a añadir
ResultObject<-Estado de la operación addFlags

Descripción

The .addFlags() function adds flags to the msgIDs for the specified keywords.

In the msgIDs parameter, you can pass either:

  • a collection containing the unique IDs of specific messages or
  • the unique ID (text) of a single message or
  • the following constant (longint) for all messages in the selected mailbox:
ConstanteValorComentario
IMAP all1Seleccionar todos los mensajes del buzón seleccionado

The keywords parameter lets you define the flags to add to msgIDs. Puede utilizar las siguientes banderas estándar, así como banderas personalizadas (la compatibilidad con banderas personalizadas depende de la implementación del servidor):

PropiedadTipoDescripción
$draftBooleanTrue para añadir el marcador "draft" al mensaje
$seenBooleanTrue para añadir el marcador "seen" al mensaje
$flaggedBooleanTrue para añadir el marcador "flagged" al mensaje
$answeredBooleanTrue para añadir el marcador "answered" al mensaje
$deletedBooleanTrue para añadir el marcador "deleted" al mensaje
<custom flag>BooleanTrue para añadir la bandera personalizada al mensaje

Los nombres de las banderas personalizadas deben respetar esta regla: la palabra clave debe ser una cadena que no distinga entre mayúsculas y minúsculas, excluyendo los caracteres de control y el espacio, y no puede incluir ninguno de estos caracteres: ( ) { ] % * " \

  • Para que una palabra clave se tenga en cuenta tiene que ser true.
  • La interpretación de los indicadores de palabras claves puede variar según el cliente de correo.

Objeto devuelto

La función devuelve un objeto que describe el estado IMAP:

PropiedadTipoDescripción
successBooleanTrue si la operación tiene éxito, False en caso contrario
statusTextTextMensaje de estado devuelto por el servidor IMAP, o último error devuelto en la pila de errores 4D
errorsCollectionPila de errores 4D (no se devuelve si se recibe una respuesta del servidor IMAP)
[].errcodeNumberCódigo de error 4D
[].messageTextDescripción del error 4D
[].componentSignatureTextFirma del componente interno que ha devuelto el error

Ejemplo

var $options;$transporter;$boxInfo;$status : Object

$options:=New object
$options.host:="imap.gmail.com"
$options.port:=993
$options.user:="4d@gmail.com"
$options.password:="xxxxx"

// Crear transportador
$transporter:=IMAP New transporter($options)

// Seleccionar buzón de correo
$boxInfo:=$transporter.selectBox("INBOX")

// Marcar todos los mensajes de INBOX como leídos/vistos
$flags:=New object
$flags["$seen"]:=True
$status:=$transporter.addFlags(IMAP all;$flags)

.append()

Historia
LanzamientoModificaciones
18 R6Añadidos

.append( mailObj : Object ; destinationBox : Text ; options : Object ) : Object

ParámetrosTipoDescripción
mailObjObject->Objeto Email
destinationBoxText->Buzón para recibir el objeto Email
optionsObject->Objeto que contiene información del charset
ResultObject<-Estado de la operación

Descripción

The .append() function appends a mailObj to the destinationBox.

In the mailObj parameter, pass an Email object. For a comprehensive description of mail properties, see Email object. The .append() function supports keyword tags in the Email object's keywords attribute.

The optional destinationBox parameter lets you pass the name of a mailbox where the mailObj will be appended. Si se omite, se utiliza el buzón actual.

In the optional options parameter, you can pass an object to define the charset and encoding for specific parts of the email. Propiedades disponibles:

PropiedadTipoDescripción
headerCharsetTextCharset y codificación utilizados para las siguientes partes del correo electrónico: asunto, nombres de archivos adjuntos y atributo(s) del nombre del correo electrónico. Valores posibles: ver la tabla de charsets posibles a continuación
bodyCharsetTextCharset y codificación utilizados para el contenido html y el texto del cuerpo del correo electrónico. Valores posibles: ver la tabla de charsets posibles a continuación

Charsets 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 si es posible, de lo contrario UTF-8 & Quoted-printable (valor por defecto)
mail mode UTF8 in base64US-ASCII_UTF8_B64headerCharset & bodyCharset: US-ASCII si es posible, de lo contrario UTF-8 & base64

Objeto devuelto

La función devuelve un objeto que describe el estado IMAP:

PropiedadTipoDescripción
successBooleanTrue si la operación tiene éxito, False en caso contrario
statusTextTextMensaje de estado devuelto por el servidor IMAP, o último error devuelto en la pila de errores 4D
errorsCollectionPila de errores 4D (no se devuelve si se recibe una respuesta del servidor IMAP)
[].errcodeNumberCódigo de error 4D
[].messageTextDescripción del error 4D
[].componentSignatureTextFirma del componente interno que ha devuelto el error

Ejemplo

Para guardar un correo electrónico en el buzón de borradores:

var $settings; $status; $msg; $imap: Object

$settings:=New object("host"; "domain.com"; "user"; "xxxx"; "password"; "xxxx"; "port"; 993)

$imap:=IMAP New transporter($settings)

$msg:=New object
$msg.from:="xxxx@domain.com"
$msg.subject:="Lorem Ipsum"
$msg.textBody:="Lorem ipsum dolor sit amet, consectetur adipiscing elit."
$msg.keywords:=New object
$msg.keywords["$seen"]:=True//flag the message as read
$msg.keywords["$draft"]:=True//flag the message as a draft

$status:=$imap.append($msg; "Drafts")

.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-MD5IMAP authentication CRAM MD5Autenticación utilizando el protocolo CRAM-MD5
LOGINIMAP authentication loginAutenticación utilizando el protocolo LOGIN
OAUTH2IMAP authentication OAUTH2Autenticación utilizando el protocolo OAuth2
PLAINIMAP authentication plainAutenticación utilizando el protocolo PLAIN

.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

.checkConnectionDelay

Historia
LanzamientoModificaciones
18 R4Añadidos

.checkConnectionDelay : Integer

Descripción

The .checkConnectionDelay property contains the maximum time (in seconds) allowed prior to checking the connection to the server. Si se supera este tiempo entre dos llamadas al método, se comprobará la conexión con el servidor. By default, if the property has not been set in the server object, the value is 300.

Warning: Make sure the defined timeout is lower than the server timeout, otherwise the client timeout will be useless.

.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.

.copy()

Historia
LanzamientoModificaciones
18 R5Añadidos

.copy( msgsIDs : Collection ; destinationBox : Text ) : Object
.copy( allMsgs : Integer ; destinationBox : Text ) : Object

ParámetrosTipoDescripción
msgsIDsCollection->Colección de identificadores únicos de mensajes (cadenas)
allMsgsInteger->IMAP all: All messages in the selected mailbox
destinationBoxText->Buzón para recibir mensajes copiados
ResultObject<-Estado de la operación de copia

Descripción

The .copy() function copies the messages defined by msgsIDs or allMsgs to the destinationBox on the IMAP server.

Puede pasar:

  • in the msgsIDs parameter, a collection containing the unique IDs of the specific messages to copy, or
  • in the allMsgs parameter, the IMAP all constant (integer) to copy all messages in the selected mailbox.

The destinationBox parameter allows you to pass a text value with the name of the mailbox where the copies of messages will be placed.

Objeto devuelto

La función devuelve un objeto que describe el estado IMAP:

PropiedadTipoDescripción
successBooleanTrue si la operación tiene éxito, False en caso contrario
statusTextTextMensaje de estado devuelto por el servidor IMAP, o último error devuelto en la pila de errores 4D
errorsCollectionPila de errores 4D (no se devuelve si se recibe una respuesta del servidor IMAP)
[].errcodeNumberCódigo de error 4D
[].messageTextDescripción del error 4D
[].componentSignatureTextFirma del componente interno que ha devuelto el error

Ejemplo 1

Para copiar una selección de mensajes:

 var $server;$boxInfo;$status : Object
var $mailIds : Collection
var $transporter : 4D.IMAPTransporter

$server:=New object
$server.host:="imap.gmail.com" //Mandatory
$server.port:=993
$server.user:="4d@gmail.com"
$server.password:="XXXXXXXX"

$transporter:=IMAP New transporter($server)

//select mailbox
$boxInfo:=$transporter.selectBox("inbox")

//get collection of message unique IDs
$mailIds:=$transporter.searchMails("subject \"4D new feature:\"")

// copy found messages to the "documents" mailbox
$status:=$transporter.copy($mailIds;"documents")

Ejemplo 2

Para copiar todos los mensajes del buzón actual:

 var $server;$boxInfo;$status : Object
var $transporter : 4D.IMAPTransporter

$server:=New object
$server.host:="imap.gmail.com" //Mandatory
$server.port:=993
$server.user:="4d@gmail.com"
$server.password:="XXXXXXXX"

$transporter:=IMAP New transporter($server)

//select mailbox

$boxInfo:=$transporter.selectBox("inbox")

// copy all messages to the "documents" mailbox
$status:=$transporter.copy(IMAP all;"documents")

.createBox()

Historia
LanzamientoModificaciones
19Añadidos

.createBox( name : Text ) : Object

ParámetrosTipoDescripción
nameText->Nombre del nuevo buzón
ResultObject<-Estado de la operación de creación del buzón

Descripción

The .createBox() function creates a mailbox with the given name. Si el caracter separador de jerarquía del servidor IMAP aparece en otra parte del nombre del buzón, el servidor IMAP creará todos los nombre padre necesarios para crear el buzón dado.

En otras palabras, un intento de crear "Projects/IMAP/Doc" en un servidor en el que "/" es el carácter separador de jerarquía creará:

  • Only the "Doc" mailbox if "Projects" & "IMAP" already exist.
  • "IMAP" & "Doc" mailboxes if only “Projects” already exists.
  • "Projects" & “IMAP” & "Doc" mailboxes, if they do not already exist.

In the name parameter, pass the name of the new mailbox.

Objeto devuelto

La función devuelve un objeto que describe el estado IMAP:

PropiedadTipoDescripción
successBooleanTrue si la operación tiene éxito, False en caso contrario
statusTextTextMensaje de estado devuelto por el servidor IMAP, o último error devuelto en la pila de errores 4D
errorsCollectionPila de errores 4D (no se devuelve si se recibe una respuesta del servidor IMAP)
[].errcodeNumberCódigo de error 4D
[].messageTextDescripción del error 4D
[].componentSignatureTextFirma del componente interno que ha devuelto el error

Ejemplo

Para crear un nuevo buzón "Invoices":

var $pw : text
var $options; $transporter; $status : object

$options:=New object

$pw:=Request("Please enter your password:")
If(OK=1)
$options.host:="imap.gmail.com"
$options.user:="test@gmail.com"
$options.password:=$pw

$transporter:=IMAP New transporter($options)

$status:=$transporter.createBox("Invoices")

If ($status.success)
ALERT("Mailbox creation successful!")
Else
ALERT("Error: "+$status.statusText)
End if
End if

.delete()

Historia
LanzamientoModificaciones
18 R5Añadidos

.delete( msgsIDs : Collection ) : Object
.delete( allMsgs : Integer ) : Object

ParámetrosTipoDescripción
msgsIDsCollection->Colección de identificadores únicos de mensajes (cadenas)
allMsgsInteger->IMAP all: All messages in the selected mailbox
ResultObject<-Estado de la operación de eliminación

Descripción

The .delete() function sets the "deleted" flag for the messages defined in msgsIDs or allMsgs.

Puede pasar:

  • in the msgsIDs parameter, a collection containing the unique IDs of the specific messages to delete, or
  • in the allMsgs parameter, the IMAP all constant (integer) to delete all messages in the selected mailbox.

La ejecución de esta función no elimina realmente los mensajes. Messages with the "delete" flag can still be found by the .searchMails() function. Flagged messages are deleted from the IMAP server with the .expunge() function or by selecting another mailbox or when the transporter object (created with IMAP New transporter) is destroyed.

Objeto devuelto

La función devuelve un objeto que describe el estado IMAP:

PropiedadTipoDescripción
successBooleanTrue si la operación tiene éxito, False en caso contrario
statusTextTextMensaje de estado devuelto por el servidor IMAP, o último error devuelto en la pila de errores 4D
errorsCollectionPila de errores 4D (no se devuelve si se recibe una respuesta del servidor IMAP)
[].errcodeNumberCódigo de error 4D
[].messageTextDescripción del error 4D
[].componentSignatureTextFirma del componente interno que ha devuelto el error

Ejemplo 1

Para eliminar una selección de mensajes:

 var $server;$boxInfo;$status : Object
var $mailIds : Collection
var $transporter : 4D.IMAPTransporter

$server:=New object
$server.host:="imap.gmail.com" //Mandatory
$server.port:=993
$server.user:="4d@gmail.com"
$server.password:="XXXXXXXX"

$transporter:=IMAP New transporter($server)

//select mailbox
$boxInfo:=$transporter.selectBox("Inbox")

//get collection of message unique IDs
$mailIds:=$transporter.searchMails("subject \"Reports\"")

// Delete selected messages
$status:=$transporter.delete($mailIds)

Ejemplo 2

Para eliminar todos los mensajes del buzón actual:

 var $server;$boxInfo;$status : Object
var $transporter : 4D.IMAPTransporter

$server:=New object
$server.host:="imap.gmail.com" //Mandatory
$server.port:=993
$server.user:="4d@gmail.com"
$server.password:="XXXXXXXX"

$transporter:=IMAP New transporter($server)

//select mailbox
$boxInfo:=$transporter.selectBox("Junk Email")

// delete all messages in the current mailbox
$status:=$transporter.delete(IMAP all)

.deleteBox()

Historia
LanzamientoModificaciones
19Añadidos

.deleteBox( name : Text ) : Object

ParámetrosTipoDescripción
nameText->Nombre del buzón a eliminar
ResultObject<-Estado de la operación de eliminación del buzón

Descripción

The .deleteBox() function permanently removes the mailbox with the given name from the IMAP server. Intentar eliminar un INBOX o un buzón que no existe generará un error.

In the name parameter, pass the name of the mailbox to delete.

  • La función no puede eliminar un buzón que tiene buzones hijos si el buzón padre tiene el atributo "\Noselect".
  • Todos los mensajes del buzón eliminado también se borrarán.
  • La posibilidad de eliminar un buzón depende del servidor de correo.

Objeto devuelto

La función devuelve un objeto que describe el estado IMAP:

PropiedadTipoDescripción
successBooleanTrue si la operación tiene éxito, False en caso contrario
statusTextTextMensaje de estado devuelto por el servidor IMAP, o último error devuelto en la pila de errores 4D
errorsCollectionPila de errores 4D (no se devuelve si se recibe una respuesta del servidor IMAP)
[].errcodeNumberCódigo de error 4D
[].messageTextDescripción del error 4D
[].componentSignatureTextFirma del componente interno que ha devuelto el error

Ejemplo

Para eliminar el buzón secundario "Nova Orion Industries" del interior del buzón "Bills":

var $pw; $name : text
var $options; $transporter; $status : object

$options:=New object

$pw:=Request("Please enter your password:")

If(OK=1) $options.host:="imap.gmail.com"
$options.user:="test@gmail.com"
$options.password:=$pw

$transporter:=IMAP New transporter($options)

// delete mailbox
$name:="Bills"+$transporter.getDelimiter()+"Nova Orion Industries"
$status:=$transporter.deleteBox($name)

If ($status.success)
ALERT("Mailbox deletion successful!")
Else
ALERT("Error: "+$status.statusText)
End if
End if

.expunge()

Historia
LanzamientoModificaciones
18 R6Añadidos

.expunge() : Object

ParámetrosTipoDescripción
ResultObject<-Estado de la operación expunge

Descripción

The .expunge() function removes all messages with the "deleted" flag from the IMAP mail server. The "deleted" flag can be set with the .delete() or .addFlags() methods.

Objeto devuelto

La función devuelve un objeto que describe el estado IMAP:

PropiedadTipoDescripción
successBooleanTrue si la operación tiene éxito, False en caso contrario
statusTextTextMensaje de estado devuelto por el servidor IMAP, o último error devuelto en la pila de errores 4D
errorsCollectionPila de errores 4D (no se devuelve si se recibe una respuesta del servidor IMAP)
[].errcodeNumberCódigo de error 4D
[].messageTextDescripción del error 4D
[].componentSignatureTextFirma del componente interno que ha devuelto el error

Ejemplo

var $options;$transporter;$boxInfo;$status : Object
var $ids : Collection

$options:=New object
$options.host:="imap.gmail.com"
$options.port:=993
$options.user:="4d@gmail.com"
$options.password:="xxxxx"

// Crear transportador
$transporter:=IMAP New transporter($options)

// Seleccionar buzón
$boxInfo:=$transporter.selectBox("INBOX")

// Buscar y eliminar todos los mensajes vistos en INBOX
$ids:=$transporter.searchMails("SEEN")
$status:=$transporter.delete($ids)

// Purgar todos los mensajes marcados como borrados
$status:=$transporter.expunge()

.getBoxInfo()

Historia
LanzamientoModificaciones
20*se devuelve el id
18 R5name es opcional
18 R4Añadidos

.getBoxInfo( { name : Text }) : Object

ParámetrosTipoDescripción
nameText->Nombre del buzón
ResultObject<-objeto boxInfo

Descripción

The .getBoxInfo() function returns a boxInfo object corresponding to the current maibox, or the mailbox name. This function returns the same information as .selectBox() without changing the current mailbox.

In the optional name parameter, pass the name of the mailbox to access. El nombre representa una jerarquía inequívoca de izquierda a derecha, con niveles separados por un carácter delimitador específico. The delimiter can be found with the .getDelimiter() function.

If the mailbox name is not selectable or does not exist, the function generates an error and returns null.

Objeto devuelto

The boxInfo object returned contains the following properties:

PropiedadTipoDescripción
nametextNombre del buzón
mailCountnumberNúmero de mensajes en el buzón
mailRecentnumberNúmero de mensajes con el marcador "reciente" (que indica los mensajes nuevos)
idtextId. único del buzón

Ejemplo

 var $transporter : 4D.IMAPTransporter
$transporter:=IMAP New transporter($server)

$info:=$transporter.getBoxInfo("INBOX")
ALERT("INBOX contains "+String($info.mailRecent)+" recent emails.")

.getBoxList()

Historia
LanzamientoModificaciones
18 R4Añadidos
19Add isSubscribed parameter

.getBoxList( { parameters : Object } ) : Collection

ParámetrosTipoDescripción
parametersObject->Objeto de parámetro
ResultCollection<-Colección de objetos mailbox

Descripción

The .getBoxList() function returns a collection of mailboxes describing all of the available mailboxes. Esta función permite gestionar localmente la lista de mensajes localizados en el servidor de correo IMAP.

In the optional parameters parameter, pass an object containing values to filter the returned mailboxes. Puede pasar:

PropiedadTipoDescripción
isSubscribedBoolean
  • True to return only subscribed mailboxes
  • False to return all available mailboxes
  • Result

    Cada objeto de la colección devuelta contiene las siguientes propiedades:

    PropiedadTipoDescripción
    [].nametextNombre del buzón
    [].selectablebooleanIndicates whether or not the access rights allow the mailbox to be selected:
    • true - the mailbox can be selected
    • false - the mailbox can not be selected
    [].inferiorbooleanIndicates whether or not the access rights allow creating a lower hierachy in the mailbox:
    • true - a lower level can be created
    • false - a lower level can not be created
    [].interestingbooleanIndicates if the mailbox has been marked "interesting" by the server:
    • true - The mailbox has been marked "interesting" by the server. For example, it may contain new messages.
    • false - The mailbox has not been marked "interesting" by the server.

    Si la cuenta no contiene buzones, se devuelve una colección vacía.

    • If there is no open connection, .getBoxList() will open a connection.
    • If the connection has not been used since the designated connection delay (see IMAP New transporter), the .checkConnection( ) function is automatically called.

    Ejemplo

     var $transporter : 4D.IMAPTransporter
    $transporter:=IMAP New transporter($server)

    $boxList:=$transporter.getBoxList()

    For each($box;$boxList)
    If($box.interesting)
    $split:=Split string($box.name;$transporter.getDelimiter())
    ALERT("New emails are available in the box: "+$split[$split.length-1])
    End if
    End for each

    .getDelimiter()

    Historia
    LanzamientoModificaciones
    18 R4Añadidos

    .getDelimiter() : Text

    ParámetrosTipoDescripción
    ResultText<-Caracter delimitador de jerarquía

    Descripción

    The .getDelimiter() function returns the character used to delimit levels of hierarchy in the mailbox name.

    El delimitador es un carácter que puede utilizarse para:

    • crear buzones de nivel inferior
    • buscar más arriba o más abajo en la jerarquía del buzón

    Result

    Caracter delimitador del nombre del buzón.

    Ejemplo

     var $transporter : 4D.IMAPTransporter
    $transporter:=IMAP New transporter($server)

    $boxList:=$transporter.getBoxList()

    For each($box;$boxList)
    If($box.interesting)
    $split:=Split string($box.name;$transporter.getDelimiter())
    ALERT("New emails are available in the box: "+$split[$split.length-1])
    End if
    End for each

    .getMail()

    Historia
    LanzamientoModificaciones
    18 R4Añadidos

    .getMail( msgNumber: Integer { ; options : Object } ) : Object
    .getMail( msgID: Text { ; options : Object } ) : Object

    ParámetrosTipoDescripción
    msgNumberInteger->Número de secuencia del mensaje
    msgIDText->ID único del mensaje
    optionsObject->Instrucciones sobre la gestión de mensajes
    ResultObject<-Email object

    Descripción

    The .getMail() function returns the Email object corresponding to the msgNumber or msgID in the mailbox designated by the IMAP_transporter. Esta función permite recuperar la información sobre el email.

    En el primer parámetro, puede pasar:

    • msgNumber, an integer value indicating the sequence number of the message to retrieve or
    • msgID, a text value indicating the unique ID of the message to retrieve.

    The optional options parameter allows you pass an object defining additional instructions for handling the message. Las siguientes propiedades están disponibles:

    PropiedadTipoDescripción
    updateSeenbooleanSi True, el mensaje se marca como "visto" en el buzón. Si es False, el mensaje no se marca como "visto". Valor por defecto: True
    withBodybooleanPase True para devolver el cuerpo del mensaje. Si es False, sólo se devuelve el encabezado del mensaje. Valor por defecto: True
    • The function generates an error and returns Null if msgID designates a non-existing message,
    • If no mailbox is selected with the .selectBox() function, an error is generated,
    • If there is no open connection, .getMail() will open a connection the last mailbox specified with .selectBox()`.

    Result

    .getMail() returns an Email object with the following specific IMAP properties: id, receivedAt, and size.

    Ejemplo

    Quiere obtener el mensaje con ID = 1:

     var $server : Object
    var $info; $mail; $boxInfo : Variant
    var $transporter : 4D.IMAPTransporter

    $server:=New object
    $server.host:="imap.gmail.com" //Mandatory
    $server.port:=993
    $server.user:="4d@gmail.com"
    $server.password:="XXXXXXXX"

    //create transporter
    $transporter:=IMAP New transporter($server)

    //select mailbox
    $boxInfo:=$transporter.selectBox("Inbox")

    //get Email object with ID 1
    $mail:=$transporter.getMail(1)

    .getMails()

    Historia
    LanzamientoModificaciones
    18 R5Añadidos

    .getMails( ids : Collection { ; options : Object } ) : Object
    .getMails( startMsg : Integer ; endMsg : Integer { ; options : Object } ) : Object

    ParámetrosTipoDescripción
    idsCollection->Colección de identificadores de mensajes
    startMsgInteger->Número de secuencia del primer mensaje
    endMsgInteger->Número de secuencia del último mensaje
    optionsObject->Instrucciones sobre la gestión de mensajes
    ResultObject<-Object containing:
    • a collection of Email objects and
    • a collection of IDs or numbers for missing messages, if any

    Descripción

    The .getMails() function returns an object containing a collection of Email objects.

    First Syntax:

    .getMails( ids { ; options } ) -> result

    La primera sintaxis permite recuperar los mensajes en función de sus identificadores.

    In the ids parameter, pass a collection of IDs for the messages to return. You can get the IDs with .getMail().

    The optional options parameter allows you to define the parts of the messages to be returned. See the Options table below for a description of the available properties.

    Segunda sintaxis:

    .getMails( startMsg ; endMsg { ; options } ) -> result

    La segunda sintaxis permite recuperar los mensajes en función de un rango secuencial. Los valores pasados representan la posición de los mensajes en el buzón.

    In the startMsg parameter, pass an integer value corresponding to the number of the first message in a sequential range. If you pass a negative number (startMsg <= 0), the first message of the mailbox will be used as the beginning of the sequence.

    In the endMsg parameter, pass an integer value corresponding to the number of the last message to be included in a sequential range. If you pass a negative number (endMsg <= 0), the last message of the mailbox will be used as the end of the sequence.

    The optional options parameter allows you to define the parts of the messages to be returned.

    Options

    PropiedadTipoDescripción
    updateSeenBooleanSi True, los mensajes especificados se marcan como "vistos" en el buzón. Si False, los mensajes no se marcan como "vistos". Valor por defecto: True
    withBodyBooleanPase True para devolver el cuerpo de los mensajes específicos. Si False, sólo se devuelve los encabezados de los mensajes. Valor por defecto: True
    • If no mailbox is selected with the .selectBox() command, an error is generated.
    • If there is no open connection, .getMails() will open a connection the last mailbox specified with .selectBox().

    Result

    .getMails() returns an object containing the following collections:

    PropiedadTipoDescripción
    listaCollectionCollection of Email objects. Si no se encuentran objetos Email, se devuelve una colección vacía.
    notFoundCollectionCollection of:
    • first syntax - previously passed message IDs that do not exist
    • second syntax - sequence numbers of messages between startMsg and endMsg that do not exist
    An empty collection is returned if all messages are found.

    Ejemplo

    Quiere recuperar los 20 correos electrónicos más recientes sin cambiar el estado "visto":

     var $server,$boxInfo,$result : Object
    var $transporter : 4D.IMAPTransporter

    $server:=New object
    $server.host:="imap.gmail.com" //Mandatory
    $server.port:=993
    $server.user:="4d@gmail.com"
    $server.password:="XXXXXXXX"

    //create transporter
    $transporter:=IMAP New transporter($server)

    //select mailbox
    $boxInfo:=$transporter.selectBox("INBOX")

    If($boxInfo.mailCount>0)
    // retrieve the headers of the last 20 messages without marking them as read
    $result:=$transporter.getMails($boxInfo.mailCount-20;$boxInfo.mailCount;\
    New object("withBody";False;"updateSeen";False))
    For each($mail;$result.list)
    // ...
    End for each
    End if

    .getMIMEAsBlob()

    Historia
    LanzamientoModificaciones
    18 R4Añadidos

    .getMIMEAsBlob( msgNumber : Integer { ; updateSeen : Boolean } ) : Blob
    .getMIMEAsBlob( msgID : Text { ; updateSeen : Boolean } ) : Blob

    ParámetrosTipoDescripción
    msgNumberInteger->Número de secuencia del mensaje
    msgIDText->ID único del mensaje
    updateSeenBoolean->Si True, el mensaje se marca como "visto" en el buzón. Si False, el mensaje se deja igual.
    ResultBLOB<-Blob de la cadena MIME devuelta por el servidor de correo

    Descripción

    The .getMIMEAsBlob() function returns a BLOB containing the MIME contents for the message corresponding to the msgNumber or msgID in the mailbox designated by the IMAP_transporter.

    En el primer parámetro, puede pasar:

    • msgNumber, an integer value indicating the sequence number of the message to retrieve or
    • msgID, a text value indicating the unique ID of the message to retrieve.

    The optional updateSeen parameter allows you to specify if the message is marked as "seen" in the mailbox. Puede pasar:

    • True - to mark the message as "seen" (indicating the message has been read)
    • False - to leave the message's "seen" status untouched
    • The function returns an empty BLOB if msgNumber or msgID* designates a non-existing message,
    • If no mailbox is selected with the .selectBox() command, an error is generated,
    • If there is no open connection, .getMIMEAsBlob() will open a connection the last mailbox specified with .selectBox().

    Result

    .getMIMEAsBlob() returns a BLOB which can be archived in a database or converted to an Email object with the MAIL Convert from MIME command.

    Ejemplo

     var $server : Object
    var $boxInfo : Variant
    var $blob : Blob
    var $transporter : 4D.IMAPTransporter

    $server:=New object
    $server.host:="imap.gmail.com"
    $server.port:=993
    $server.user:="4d@gmail.com"
    $server.password:="XXXXXXXX"

    //create transporter
    $transporter:=IMAP New transporter($server)

    //select mailbox
    $boxInfo:=$transporter.selectBox("Inbox")

    //get BLOB
    $blob:=$transporter.getMIMEAsBlob(1)

    .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).

    .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:

    .move()

    Historia
    LanzamientoModificaciones
    18 R5Añadidos

    .move( msgsIDs : Collection ; destinationBox : Text ) : Object
    .move( allMsgs : Integer ; destinationBox : Text ) : Object

    ParámetrosTipoDescripción
    msgsIDsCollection->Colección de identificadores únicos de mensajes (cadenas)
    allMsgsInteger->IMAP all: All messages in the selected mailbox
    destinationBoxText->Buzón para recibir los mensajes desplazados
    ResultObject<-Estado de la operación de desplazamiento

    Descripción

    The .move() function moves the messages defined by msgsIDs or allMsgs to the destinationBox on the IMAP server.

    Puede pasar:

    • in the msgsIDs parameter, a collection containing the unique IDs of the specific messages to move, or
    • in the allMsgs parameter, the IMAP all constant (integer) to move all messages in the selected mailbox.

    The destinationBox parameter allows you to pass a text value with the name of the mailbox where the messages will be moved.

    This function is only supported by IMAP servers compliant with RFC 8474.

    Objeto devuelto

    La función devuelve un objeto que describe el estado IMAP:

    PropiedadTipoDescripción
    successBooleanTrue si la operación tiene éxito, False en caso contrario
    statusTextTextMensaje de estado devuelto por el servidor IMAP, o último error devuelto en la pila de errores 4D
    errorsCollectionPila de errores 4D (no se devuelve si se recibe una respuesta del servidor IMAP)
    [].errcodeNumberCódigo de error 4D
    [].messageTextDescripción del error 4D
    [].componentSignatureTextFirma del componente interno que ha devuelto el error

    Ejemplo 1

    Para mover una selección de mensajes:

     var $server;$boxInfo;$status : Object
    var $mailIds : Collection
    var $transporter : 4D.IMAPTransporter

    $server:=New object
    $server.host:="imap.gmail.com" //Mandatory
    $server.port:=993
    $server.user:="4d@gmail.com"
    $server.password:="XXXXXXXX"

    $transporter:=IMAP New transporter($server)

    //select mailbox
    $boxInfo:=$transporter.selectBox("inbox")

    //get collection of message unique IDs
    $mailIds:=$transporter.searchMails("subject \"4D new feature:\"")

    // Move found messages from the current mailbox to the "documents" mailbox
    $status:=$transporter.move($mailIds;"documents")

    Ejemplo 2

    Para mover todos los mensajes del buzón actual:

     var $server;$boxInfo;$status : Object
    var $transporter : 4D.IMAPTransporter

    $server:=New object
    $server.host:="imap.gmail.com" //Mandatory
    $server.port:=993
    $server.user:="4d@gmail.com"
    $server.password:="XXXXXXXX"

    $transporter:=IMAP New transporter($server)

    //select mailbox
    $boxInfo:=$transporter.selectBox("inbox")

    // move all messages in the current mailbox to the "documents" mailbox
    $status:=$transporter.move(IMAP all;"documents")

    .numToID()

    Historia
    LanzamientoModificaciones
    18 R5Añadidos

    .numToID( startMsg : Integer ; endMsg : Integer ) : Collection

    ParámetrosTipoDescripción
    startMsgInteger->Número de secuencia del primer mensaje
    endMsgInteger->Número de secuencia del último mensaje
    ResultCollection<-Colección de identificadores de mensajes únicos

    Descripción

    The .numToID() function converts the sequence numbers to IMAP unique IDs for the messages in the sequential range designated by startMsg and endMsg in the currently selected mailbox.

    In the startMsg parameter, pass an integer value corresponding to the number of the first message in a sequential range. If you pass a negative number (startMsg <= 0), the first message of the mailbox will be used as the beginning of the sequence.

    In the endMsg parameter, pass an integer value corresponding to the number of the last message to be included in a sequential range. If you pass a negative number (endMsg <= 0), the last message of the mailbox will be used as the end of the sequence.

    Result

    La función devuelve una colección de cadenas (IDs únicos).

    Ejemplo

     var $transporter : 4D.IMAPTransporter
    var $server;$boxInfo;$status : Object
    var $mailIds : Collection

    $server:=New object
    $server.host:="imap.gmail.com" //Mandatory
    $server.port:=993
    $server.user:="4d@gmail.com"
    $server.password:="XXXXXXXX"

    $transporter:=IMAP New transporter($server)

    //select mailbox
    $boxInfo:=$transporter.selectBox("inbox")

    //get IDs for 5 last messages received
    $mailIds:=$transporter.numToID(($boxInfo.mailCount-5);$boxInfo.mailCount)

    //delete the messages from the current mailbox
    $status:=$transporter.delete($mailIds)

    .removeFlags()

    Historia
    LanzamientoModificaciones
    20Soporta palabras claves personalizadas
    18 R6Añadidos

    .removeFlags( msgIDs : Collection ; keywords : Object ) : Object
    .removeFlags( msgIDs : Text ; keywords : Object ) : Object
    .removeFlags( msgIDs : Longint ; keywords : Object ) : Object

    ParámetrosTipoDescripción
    msgIDsCollection->Colección de cadenas: identificadores únicos de mensajes (texto)
    Texto: ID único de un mensaje
    Longint (IMAP all): todos los mensajes del buzón seleccionado
    keywordsObject->Banderas de palabras claves a eliminar
    ResultObject<-Estado de la operación removeFlags

    Descripción

    The .removeFlags() function removes flags from the msgIDs for the specified keywords.

    In the msgIDs parameter, you can pass either:

    • a collection containing the unique IDs of specific messages or
    • the unique ID (text) of a single message or
    • the following constant (longint) for all messages in the selected mailbox:
    ConstanteValorComentario
    IMAP all1Seleccionar todos los mensajes del buzón seleccionado

    The keywords parameter lets you define the flags to remove from msgIDs. Puede utilizar las siguientes banderas estándar, así como banderas personalizadas:

    ParámetrosTipoDescripción
    $draftBooleanTrue para eliminar el marcador "draft" del mensaje
    $seenBooleanTrue para eliminar el marcador "seen" del mensaje
    $flaggedBooleanTrue para eliminar el marcador "flagged" del mensaje
    $answeredBooleanTrue para eliminar el marcador "answered" del mensaje
    $deletedBooleanTrue para eliminar el marcador "deleted" del mensaje
    <custom flag>BooleanTrue para eliminar la bandera personalizada del mensaje

    Please refer to .addFlags() for more information on custom flags.

    • Para que una palabra clave se tenga en cuenta tiene que ser true.

    Objeto devuelto

    La función devuelve un objeto que describe el estado IMAP:

    PropiedadTipoDescripción
    successBooleanTrue si la operación tiene éxito, False en caso contrario
    statusTextTextMensaje de estado devuelto por el servidor IMAP, o último error devuelto en la pila de errores 4D
    errorsCollectionPila de errores 4D (no se devuelve si se recibe una respuesta del servidor IMAP)
    [].errcodeNumberCódigo de error 4D
    [].messageTextDescripción del error 4D
    [].componentSignatureTextFirma del componente interno que ha devuelto el error

    Ejemplo

    var $options;$transporter;$boxInfo;$status : Object

    $options:=New object
    $options.host:="imap.gmail.com"
    $options.port:=993
    $options.user:="4d@gmail.com"
    $options.password:="xxxxx"

    // Crear transportador
    $transporter:=IMAP New transporter($options)

    // Seleccionar buzón
    $boxInfo:=$transporter.selectBox("INBOX")

    // Marcar todos los mensajes de INBOX como no vistos
    $flags:=New object
    $flags["$seen"]:=True
    $status:=$transporter.removeFlags(IMAP all;$flags)

    .renameBox()

    Historia
    LanzamientoModificaciones
    19Añadidos

    .renameBox( currentName : Text ; newName : Text ) : Object

    ParámetrosTipoDescripción
    currentNameText->Nombre del nuevo actual
    newNameText->Nuevo nombre del buzón
    ResultObject<-Estado de la operación renombrar

    Descripción

    The .renameBox() function changes the name of a mailbox on the IMAP server. Si se intenta renombrar un buzón desde un nombre de buzón que no existe o a un nombre de buzón que ya existe, se generará un error.

    In the currentName parameter, pass the name of the mailbox to be renamed.

    Pass the new name for the mailbox in the newName parameter.

    Objeto devuelto

    La función devuelve un objeto que describe el estado IMAP:

    PropiedadTipoDescripción
    successBooleanTrue si la operación tiene éxito, False en caso contrario
    statusTextTextMensaje de estado devuelto por el servidor IMAP, o último error devuelto en la pila de errores 4D
    errorsCollectionPila de errores 4D (no se devuelve si se recibe una respuesta del servidor IMAP)
    [].errcodeNumberCódigo de error 4D
    [].messageTextDescripción del error 4D
    [].componentSignatureTextFirma del componente interno que ha devuelto el error

    Ejemplo

    Para cambiar el nombre de su buzón de "Invoices" a "Bills":

    var $pw : text
    var $options; $transporter; $status : object

    $options:=New object

    $pw:=Request("Please enter your password:")

    If(OK=1) $options.host:="imap.gmail.com"

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

    $transporter:=IMAP New transporter($options)

    // rename mailbox
    $status:=$transporter.renameBox("Invoices"; "Bills")

    If ($status.success)
    ALERT("Mailbox renaming successful!")
    Else
    ALERT("Error: "+$status.statusText)
    End if
    End if

    .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

    .searchMails()

    Historia
    LanzamientoModificaciones
    18 R5Añadidos

    .searchMails( searchCriteria : Text ) : Collection

    ParámetrosTipoDescripción
    searchCriteriaText->Criterio de búsqueda
    ResultCollection<-Colección de números de mensajes

    Descripción

    This function is based upon the specification for the IMAP protocol.

    The .searchMails() function searches for messages that match the given searchCriteria in the current mailbox. searchCriteria consists of one or more search keys.

    searchCriteria is a text parameter listing one or more search keys (see Authorized search-keys below) associated or not with values to look for. Una llave de búsqueda puede ser uno o varios elementos. Por ejemplo:

    SearchKey1 = FLAGGED
    SearchKey2 = NOT FLAGGED
    SearchKey3 = FLAGGED DRAFT

    Para obtener la información de un buzón sin cambiar el buzón actual, utilice .getBoxInfo().

    • If the searchCriteria is a null string, the search will be equivalent to a “select all”.
    • If the searchCriteria includes multiple search keys, the result is the intersection (AND function) of all the messages that match those keys.
    searchCriteria = FLAGGED FROM "SMITH"

    ... returns all messages with \Flagged flag set AND sent by Smith.

    • You can use the OR or NOT operators as follows:
    searchCriteria = OR SEEN FLAGGED

    ... devuelve todos los mensajes con el marcador \Seen O \Flagged

    searchCriteria = NOT SEEN

    ... devuelve todos los mensajes con el marcador \Seen.

    searchCriteria = HEADER CONTENT-TYPE "MIXED" NOT HEADER CONTENT-TYPE "TEXT"...

    ... returns message whose content-type header contains “Mixed” and does not contain “Text”.

    searchCriteria = HEADER CONTENT-TYPE "E" NOT SUBJECT "o" NOT HEADER CONTENT-TYPE "MIXED"

    ... returns message whose content-type header contains “ e ” and whose Subject header does not contain “ o ” and whose content-type header is not “ Mixed ”.

    En cuanto a los dos últimos ejemplos, observe que el resultado de la búsqueda es diferente cuando se eliminan los paréntesis de la primera lista de llaves de búsqueda.

    • The searchCriteria may include the optional [CHARSET] specification. Esta instrucción consiste en la palabra "CHARSET" seguida de un conjunto de caracteres definido [CHARSET] (US ASCII, ISO-8859). It indicates the charset of the searchCriteria string. Therefore, you must convert the searchCriteria string into the specified charset if you use the [CHARSET] specification (see the CONVERT FROM TEXT or Convert to text commands). Por defecto, 4D codifica la cadena de criterios searchCriteria en Quotable Printable si contiene los caracteres extendidos.
    searchCriteria = CHARSET "ISO-8859" BODY "Help"

    ... significa que los criterios de búsqueda utilizan el conjunto de caracteres iso-8859 y el servidor tendrá que convertir los criterios de búsqueda antes de buscar, si es necesario.

    Tipos de valores de búsqueda

    Las claves de búsqueda pueden solicitar el valor a buscar:

    • Search-keys with a date value: the date is a string that must be formatted as follows: date-day+"-"+date-month+"-"+date-year where date-day indicates the number of the day of the month (max. 2 characters), date-month indicates the name of the month (Jan/Feb/Mar/Apr/May/Jun/Jul/Aug/Sep/Oct/Dec) and date-year indicates the year (4 characters). Example: searchCriteria = SENTBEFORE 1-Feb-2020 (a date does not usually need to be quoted since it does not contain any special characters)

    • Search-keys with a string value: the string may contain any character and must be quoted. Si la cadena no contiene ningún caracter especial, como el espacio, por ejemplo, no es necesario colocarla entre comillas. Al colocar entre comillas estas cadenas se garantiza que su valor se interpretará correctamente. Example: searchCriteria = FROM "SMITH" For all search keys that use strings, a message matches the key if the string is a substring of the field. Las coincidencias no diferencian entre mayúsculas y minúsculas.

    • Search-keys with a field-name value: the field-name is the name of a header field. Example: searchCriteria = HEADER CONTENT-TYPE "MIXED"

    • Search-keys with a flag value: the flag may accept one or several keywords (including standard flags), separated by spaces. Example: searchCriteria = KEYWORD \Flagged \Draft

    • Search-keys with a message set value: Identifies a set of messages. En el caso de los números de secuencia de los mensajes, se trata de números consecutivos desde el 1 hasta el número total de mensajes en el buzón. Los números son separados por coma; un dos puntos (:) delimita entre dos números inclusive. Examples: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,14,15 for a mailbox with 15 messages. searchCriteria = 1:5 ANSWERED search in message selection from message sequence number 1 to 5 for messages which have the \Answered flag set. searchCriteria= 2,4 ANSWERED search in the message selection (message numbers 2 and 4) for messages which have the \Answered flag set.

    Teclas de búsqueda disponibles

    ALL: All messages in the mailbox.\ ANSWERED: Messages with the \Answered flag set.\ UNANSWERED: Messages that do not have the \Answered flag set.\ DELETED: Messages with the \Deleted flag set.\ UNDELETED: Messages that do not have the \Deleted flag set.\ DRAFT: Messages with the \Draft flag set.\ UNDRAFT: Messages that do not have the \Draft flag set.\ FLAGGED: Messages with the \Flagged flag set.\ UNFLAGGED: Messages that do not have the \Flagged flag set.\ RECENT: Messages that have the \Recent flag set.\ OLD: Messages that do not have the \Recent flag set.\ SEEN: Messages that have the \Seen flag set.\ UNSEEN: Messages that do not have the \Seen flag set.\ NEW: Messages that have the \Recent flag set but not the \Seen flag. This is functionally equivalent to “(RECENT UNSEEN)”.\ KEYWORD flag: Messages with the specified keyword set.\ UNKEYWORD flag: Messages that do not have the specified keyword set.\ BEFORE date: Messages whose internal date is earlier than the specified date.\ ON date: Messages whose internal date is within the specified date.\ SINCE date: Messages whose internal date is within or later than the specified date.\ SENTBEFORE date: Messages whose Date header is earlier than the specified date.\ SENTON date: Messages whose Date header is within the specified date.\ SENTSINCE date: Messages whose Date header is within or later than the specified date.\ TO string: Messages that contain the specified string in the TO header.\ FROM string: Messages that contain the specified string in the FROM header.\ CC string: Messages that contain the specified string in the CC header.\ BCC string: Messages that contain the specified string in the BCC header.\ SUBJECT string: Messages that contain the specified string in the Subject header.\ BODY string: Messages that contain the specified string in the message body.\ TEXT string: Messages that contain the specified string in the header or in the message body.\ HEADER field-name string: Messages that have a header with the specified field-name and that contain the specified string in the field-body.\ UID message-UID: Messages with unique identifiers corresponding to the specified unique identifier set.\ LARGER n: Messages with a size larger than the specified number of bytes.\ SMALLER n: Messages with a size smaller than the specified number of bytes.\ NOT search-key: Messages that do not match the specified search key.\ OR search-key1 search-key2: Messages that match either search key.

    .selectBox()

    Historia
    LanzamientoModificaciones
    20id, flags, permanentFlags are returned
    18 R4Añadidos

    .selectBox( name : Text { ; state : Integer } ) : Object

    ParámetrosTipoDescripción
    nameText->Nombre del buzón
    stateInteger->Estado de acceso al buzón
    ResultObject<-objeto boxInfo

    Descripción

    The .selectBox() function selects the name mailbox as the current mailbox. Esta función permite recuperar la información sobre el buzón.

    To get the information from a mailbox without changing the current mailbox, use .getBoxInfo().

    In the name parameter, pass the name of the mailbox to access. El nombre representa una jerarquía inequívoca de izquierda a derecha, con niveles separados por un carácter delimitador específico. The delimiter can be found with the .getDelimiter() function.

    The optional state parameter defines the type of access to the mailbox. Los valores posibles son:

    ConstanteValorComentario
    IMAP read only state1Se accede al buzón seleccionado con privilegios de sólo lectura. Los mensajes con la bandera "reciente" (que indica que son nuevos) no se modifican.
    IMAP read write state0Se accede al buzón seleccionado con privilegios de lectura y escritura. Los mensajes se consideran "vistos" y pierden la bandera "reciente" (que indica que son mensajes nuevos). Default value:
    • The function generates an error and returns Null if name designates a non-existing mailbox.
    • If there is no open connection, .selectBox() will open a connection.
    • If the connection has not been used since the designated connection delay (see IMAP New transporter), the .checkConnection() function is automatically called.

    Objeto devuelto

    The boxInfo object returned contains the following properties:

    PropiedadTipoDescripción
    nameTextNombre del buzón
    mailCountnumberNúmero de mensajes en el buzón
    mailRecentnumberNúmero de mensajes con la bandera "recent"
    idtextId. único del buzón
    flagstextLista de banderas utilizadas actualmente para el buzón, separadas por espacios
    permanentFlagstextLista de banderas que el cliente puede cambiar permanentemente (excepto el indicador \Recent, que gestiona el servidor IMAP), separados por espacios
    info

    If permanentFlags string includes the special flag *, it means that the server supports custom flags.

    Ejemplo

     var $server; $boxinfo : Object
    $server:=New object
    $server.host:="imap.gmail.com" //Mandatory
    $server.user:="4d@gmail.com"
    $server.password:="XXXXXXXX"

    var $transporter : 4D.IMAPTransporter
    $transporter:=IMAP New transporter($server)
    $boxInfo:=$transporter.selectBox("INBOX")

    .subscribe()

    Historia
    LanzamientoModificaciones
    19Añadidos

    .subscribe( name : Text ) : Object

    ParámetrosTipoDescripción
    nameText->Nombre del buzón
    ResultObject<-Estado de la operación subscribe

    Descripción

    The .subscribe() function allows adding or removing of the specified mailbox to/from the IMAP server’s set of “subscribed” mailboxes. De este modo, puede optar por acotar una gran lista de buzones disponibles suscribiéndose a los que habitualmente consulta.

    In the name parameter, pass the name of the mailbox to add (subscribe) to your "subscribed" mailboxes.

    Objeto devuelto

    La función devuelve un objeto que describe el estado IMAP:

    PropiedadTipoDescripción
    successBooleanTrue si la operación tiene éxito, False en caso contrario
    statusTextTextMensaje de estado devuelto por el servidor IMAP, o último error devuelto en la pila de errores 4D
    errorsCollectionPila de errores 4D (no se devuelve si se recibe una respuesta del servidor IMAP)
    [].errcodeNumberCódigo de error 4D
    [].messageTextDescripción del error 4D
    [].componentSignatureTextFirma del componente interno que ha devuelto el error

    Ejemplo

    Para suscribirse al buzón "Atlas Corp" en la jerarquía "Bills":

    var $pw; $name : text
    var $options; $transporter; $status : object

    $options:=New object

    $pw:=Request("Please enter your password:")

    If(OK=1) $options.host:="imap.gmail.com"
    $options.user:="test@gmail.com"
    $options.password:=$pw

    $transporter:=IMAP New transporter($options)

    $name:="Bills"+$transporter.getDelimiter()+"Atlas Corp"
    $status:=$transporter.subscribe($name)

    If ($status.success)
    ALERT("Mailbox subscription successful!")
    Else
    ALERT("Error: "+$status.statusText)
    End if
    End if

    .unsubscribe()

    Historia
    LanzamientoModificaciones
    19Añadidos

    .unsubscribe( name : Text ) : Object

    ParámetrosTipoDescripción
    nameText->Nombre del buzón
    ResultObject<-Estado de la operación unsubscribe

    Descripción

    The .unsubscribe() function removes a mailbox from a set of subscribed mailboxes. Esto le permite reducir el número de buzones que suele ver.

    In the name parameter, pass the name of the mailbox to remove (unsubscribe) from your active mailboxes.

    Objeto devuelto

    La función devuelve un objeto que describe el estado IMAP:

    PropiedadTipoDescripción
    successBooleanTrue si la operación tiene éxito, False en caso contrario
    statusTextTextMensaje de estado devuelto por el servidor IMAP, o último error devuelto en la pila de errores 4D
    errorsCollectionPila de errores 4D (no se devuelve si se recibe una respuesta del servidor IMAP)
    [].errcodeNumberCódigo de error 4D
    [].messageTextDescripción del error 4D
    [].componentSignatureTextFirma del componente interno que ha devuelto el error

    Ejemplo

    Para desuscribirse del buzón "Atlas Corp" en la jerarquía "Bills":

    var $pw; $name : text
    var $options; $transporter; $status : object

    $options:=New object

    $pw:=Request("Please enter your password:")

    If(OK=1) $options.host:="imap.gmail.com"
    $options.user:="test@gmail.com"
    $options.password:=$pw

    $transporter:=IMAP New transporter($options)

    $name:="Bills"+$transporter.getDelimiter()+"Atlas Corp"
    $status:=$transporter.unsubscribe($name)

    If ($status.success)
    ALERT("Mailbox unsubscription successful!")
    Else
    ALERT("Error: "+$status.statusText)
    End if
    End if

    .user

    Historia
    LanzamientoModificaciones
    17 R4Añadidos

    .user : Text

    Descripción

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