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
Lanzamiento | Modificaciones |
---|---|
18 R4 | Añadidos |
IMAP New transporter( server : Object ) : 4D.IMAPTransporter
Parámetros | Tipo | Descripción | |
---|---|---|---|
server | Object | -> | Información del servidor de correo |
Result | 4D.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:
server | Valor por defecto (si se omite) |
---|---|
.acceptUnsecureConnection : Boolean True if 4D is allowed to establish an unencrypted connection | False |
.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 the authentication mode used to open the session on the mail server | se utiliza el modo de autenticación más seguro soportado por el servidor |
.checkConnectionDelay : Integer the maximum time (in seconds) allowed prior to checking the connection to the server | 300 |
.connectionTimeOut : Integer the maximum wait time (in seconds) allowed to establish a connection to the server | 30 |
.host : Text the name or the IP address of the host server | obligatorio |
.logFile : Text the path of the extended log file defined (if any) for the mail connection | ninguno |
.password : Text User password for authentication on the server. Not returned in IMAP transporter object. | ninguno |
.port : Integer the port number used for mail transactions | 993 |
.user : Text the user name used for authentication on the mail server | ninguno |
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ámetros | Tipo | Descripción | |
---|---|---|---|
server | Object | -> | Información del servidor de correo |
Result | 4D.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
Lanzamiento | Modificaciones |
---|---|
17 R4 | Añ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
Lanzamiento | Modificaciones |
---|---|
20 | Soporta palabras claves personalizadas |
18 R6 | Añadidos |
.addFlags( msgIDs : Collection ; keywords : Object ) : Object
.addFlags( msgIDs : Text ; keywords : Object ) : Object
.addFlags( msgIDs : Longint ; keywords : Object ) : Object
Parámetros | Tipo | Descripción | |
---|---|---|---|
msgIDs | Collection | -> | 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 |
keywords | Object | -> | Banderas de palabras claves a añadir |
Result | Object | <- | 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:
Constante | Valor | Comentario |
---|---|---|
IMAP all | 1 | Seleccionar 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):
Propiedad | Tipo | Descripción |
---|---|---|
$draft | Boolean | True para añadir el marcador "draft" al mensaje |
$seen | Boolean | True para añadir el marcador "seen" al mensaje |
$flagged | Boolean | True para añadir el marcador "flagged" al mensaje |
$answered | Boolean | True para añadir el marcador "answered" al mensaje |
$deleted | Boolean | True para añadir el marcador "deleted" al mensaje |
<custom flag> | Boolean | True 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:
Propiedad | Tipo | Descripción | |
---|---|---|---|
success | Boolean | True si la operación tiene éxito, False en caso contrario | |
statusText | Text | Mensaje de estado devuelto por el servidor IMAP, o último error devuelto en la pila de errores 4D | |
errors | Collection | Pila de errores 4D (no se devuelve si se recibe una respuesta del servidor IMAP) | |
[].errcode | Number | Código de error 4D | |
[].message | Text | Descripción del error 4D | |
[].componentSignature | Text | Firma 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
Lanzamiento | Modificaciones |
---|---|
18 R6 | Añadidos |
.append( mailObj : Object ; destinationBox : Text ; options : Object ) : Object
Parámetros | Tipo | Descripción | |
---|---|---|---|
mailObj | Object | -> | Objeto Email |
destinationBox | Text | -> | Buzón para recibir el objeto Email |
options | Object | -> | Objeto que contiene información del charset |
Result | Object | <- | 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:
Propiedad | Tipo | Descripción |
---|---|---|
headerCharset | Text | Charset 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 |
bodyCharset | Text | Charset 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:
Constante | Valor | Comentario |
---|---|---|
mail mode ISO2022JP | US-ASCII_ISO-2022-JP_UTF8_QP |
|
mail mode ISO88591 | ISO-8859-1 |
|
mail mode UTF8 | US-ASCII_UTF8_QP | headerCharset & bodyCharset: US-ASCII si es posible, de lo contrario UTF-8 & Quoted-printable (valor por defecto) |
mail mode UTF8 in base64 | US-ASCII_UTF8_B64 | headerCharset & 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:
Propiedad | Tipo | Descripción | |
---|---|---|---|
success | Boolean | True si la operación tiene éxito, False en caso contrario | |
statusText | Text | Mensaje de estado devuelto por el servidor IMAP, o último error devuelto en la pila de errores 4D | |
errors | Collection | Pila de errores 4D (no se devuelve si se recibe una respuesta del servidor IMAP) | |
[].errcode | Number | Código de error 4D | |
[].message | Text | Descripción del error 4D | |
[].componentSignature | Text | Firma 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
Lanzamiento | Modificaciones |
---|---|
17 R4 | Añ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:
Valor | Constantes | Comentario |
---|---|---|
CRAM-MD5 | IMAP authentication CRAM MD5 | Autenticación utilizando el protocolo CRAM-MD5 |
LOGIN | IMAP authentication login | Autenticación utilizando el protocolo LOGIN |
OAUTH2 | IMAP authentication OAUTH2 | Autenticación utilizando el protocolo OAuth2 |
PLAIN | IMAP authentication plain | Autenticación utilizando el protocolo PLAIN |
.checkConnection()
Historia
Lanzamiento | Modificaciones |
---|---|
17 R4 | Añadidos |
.checkConnection() : Object
Parámetros | Tipo | Descripción | |
---|---|---|---|
Result | Object | <- | 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:
Propiedad | Tipo | Descripción | |
---|---|---|---|
success | boolean | True si la verificación es exitosa, False en caso contrario | |
status | number | (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) | |
statusText | text | Mensaje de estado devuelto por el servidor de correo, o último error devuelto en la pila de errores de 4D | |
errors | collection | Pila de errores 4D (no se devuelve si se recibe una respuesta del servidor de correo) | |
[ ].errCode | number | Código de error 4D | |
[ ].message | text | Descripción del error 4D | |
[ ].componentSignature | text | Firma del componente interno que ha devuelto el error |
.checkConnectionDelay
Historia
Lanzamiento | Modificaciones |
---|---|
18 R4 | Añ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
Lanzamiento | Modificaciones |
---|---|
17 R5 | Añ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
Lanzamiento | Modificaciones |
---|---|
18 R5 | Añadidos |
.copy( msgsIDs : Collection ; destinationBox : Text ) : Object
.copy( allMsgs : Integer ; destinationBox : Text ) : Object
Parámetros | Tipo | Descripción | |
---|---|---|---|
msgsIDs | Collection | -> | Colección de identificadores únicos de mensajes (cadenas) |
allMsgs | Integer | -> | IMAP all : All messages in the selected mailbox |
destinationBox | Text | -> | Buzón para recibir mensajes copiados |
Result | Object | <- | 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:
Propiedad | Tipo | Descripción | |
---|---|---|---|
success | Boolean | True si la operación tiene éxito, False en caso contrario | |
statusText | Text | Mensaje de estado devuelto por el servidor IMAP, o último error devuelto en la pila de errores 4D | |
errors | Collection | Pila de errores 4D (no se devuelve si se recibe una respuesta del servidor IMAP) | |
[].errcode | Number | Código de error 4D | |
[].message | Text | Descripción del error 4D | |
[].componentSignature | Text | Firma 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
Lanzamiento | Modificaciones |
---|---|
19 | Añadidos |
.createBox( name : Text ) : Object
Parámetros | Tipo | Descripción | |
---|---|---|---|
name | Text | -> | Nombre del nuevo buzón |
Result | Object | <- | 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:
Propiedad | Tipo | Descripción | |
---|---|---|---|
success | Boolean | True si la operación tiene éxito, False en caso contrario | |
statusText | Text | Mensaje de estado devuelto por el servidor IMAP, o último error devuelto en la pila de errores 4D | |
errors | Collection | Pila de errores 4D (no se devuelve si se recibe una respuesta del servidor IMAP) | |
[].errcode | Number | Código de error 4D | |
[].message | Text | Descripción del error 4D | |
[].componentSignature | Text | Firma 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
Lanzamiento | Modificaciones |
---|---|
18 R5 | Añadidos |
.delete( msgsIDs : Collection ) : Object
.delete( allMsgs : Integer ) : Object
Parámetros | Tipo | Descripción | |
---|---|---|---|
msgsIDs | Collection | -> | Colección de identificadores únicos de mensajes (cadenas) |
allMsgs | Integer | -> | IMAP all : All messages in the selected mailbox |
Result | Object | <- | 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, theIMAP 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:
Propiedad | Tipo | Descripción | |
---|---|---|---|
success | Boolean | True si la operación tiene éxito, False en caso contrario | |
statusText | Text | Mensaje de estado devuelto por el servidor IMAP, o último error devuelto en la pila de errores 4D | |
errors | Collection | Pila de errores 4D (no se devuelve si se recibe una respuesta del servidor IMAP) | |
[].errcode | Number | Código de error 4D | |
[].message | Text | Descripción del error 4D | |
[].componentSignature | Text | Firma 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
Lanzamiento | Modificaciones |
---|---|
19 | Añadidos |
.deleteBox( name : Text ) : Object
Parámetros | Tipo | Descripción | |
---|---|---|---|
name | Text | -> | Nombre del buzón a eliminar |
Result | Object | <- | 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:
Propiedad | Tipo | Descripción | |
---|---|---|---|
success | Boolean | True si la operación tiene éxito, False en caso contrario | |
statusText | Text | Mensaje de estado devuelto por el servidor IMAP, o último error devuelto en la pila de errores 4D | |
errors | Collection | Pila de errores 4D (no se devuelve si se recibe una respuesta del servidor IMAP) | |
[].errcode | Number | Código de error 4D | |
[].message | Text | Descripción del error 4D | |
[].componentSignature | Text | Firma 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
Lanzamiento | Modificaciones |
---|---|
18 R6 | Añadidos |
.expunge() : Object
Parámetros | Tipo | Descripción | |
---|---|---|---|
Result | Object | <- | 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:
Propiedad | Tipo | Descripción | |
---|---|---|---|
success | Boolean | True si la operación tiene éxito, False en caso contrario | |
statusText | Text | Mensaje de estado devuelto por el servidor IMAP, o último error devuelto en la pila de errores 4D | |
errors | Collection | Pila de errores 4D (no se devuelve si se recibe una respuesta del servidor IMAP) | |
[].errcode | Number | Código de error 4D | |
[].message | Text | Descripción del error 4D | |
[].componentSignature | Text | Firma 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
Lanzamiento | Modificaciones |
---|---|
20 | *se devuelve el id |
18 R5 | name es opcional |
18 R4 | Añadidos |
.getBoxInfo( { name : Text }) : Object
Parámetros | Tipo | Descripción | |
---|---|---|---|
name | Text | -> | Nombre del buzón |
Result | Object | <- | 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:
Propiedad | Tipo | Descripción |
---|---|---|
name | text | Nombre del buzón |
mailCount | number | Número de mensajes en el buzón |
mailRecent | number | Número de mensajes con el marcador "reciente" (que indica los mensajes nuevos) |
id | text | Id. ú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
Lanzamiento | Modificaciones |
---|---|
18 R4 | Añadidos |
19 | Add isSubscribed parameter |
.getBoxList( { parameters : Object } ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
parameters | Object | -> | Objeto de parámetro |
Result | Collection | <- | 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:
Propiedad | Tipo | Descripción |
---|---|---|
isSubscribed | Boolean |
Result
Cada objeto de la colección devuelta contiene las siguientes propiedades:
Propiedad | Tipo | Descripción |
---|---|---|
[].name | text | Nombre del buzón |
[].selectable | boolean | Indicates whether or not the access rights allow the mailbox to be selected:
|
[].inferior | boolean | Indicates whether or not the access rights allow creating a lower hierachy in the mailbox:
|
[].interesting | boolean | Indicates if the mailbox has 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
Lanzamiento | Modificaciones |
---|---|
18 R4 | Añadidos |
.getDelimiter() : Text
Parámetros | Tipo | Descripción | |
---|---|---|---|
Result | Text | <- | 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.
- If there is no open connection,
.getDelimiter()
will open a connection.- If the connection has not been used since the designated connection delay, 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
.getMail()
Historia
Lanzamiento | Modificaciones |
---|---|
18 R4 | Añadidos |
.getMail( msgNumber: Integer { ; options : Object } ) : Object
.getMail( msgID: Text { ; options : Object } ) : Object
Parámetros | Tipo | Descripción | |
---|---|---|---|
msgNumber | Integer | -> | Número de secuencia del mensaje |
msgID | Text | -> | ID único del mensaje |
options | Object | -> | Instrucciones sobre la gestión de mensajes |
Result | Object | <- | 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:
Propiedad | Tipo | Descripción |
---|---|---|
updateSeen | boolean | Si 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 |
withBody | boolean | Pase 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
Lanzamiento | Modificaciones |
---|---|
18 R5 | Añadidos |
.getMails( ids : Collection { ; options : Object } ) : Object
.getMails( startMsg : Integer ; endMsg : Integer { ; options : Object } ) : Object
Parámetros | Tipo | Descripción | |
---|---|---|---|
ids | Collection | -> | Colección de identificadores de mensajes |
startMsg | Integer | -> | Número de secuencia del primer mensaje |
endMsg | Integer | -> | Número de secuencia del último mensaje |
options | Object | -> | Instrucciones sobre la gestión de mensajes |
Result | Object | <- | Object containing:
|
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
Propiedad | Tipo | Descripción |
---|---|---|
updateSeen | Boolean | Si 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 |
withBody | Boolean | Pase 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:
Propiedad | Tipo | Descripción |
---|---|---|
lista | Collection | Collection of Email objects. Si no se encuentran objetos Email, se devuelve una colección vacía. |
notFound | Collection | Collection of:
|
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
Lanzamiento | Modificaciones |
---|---|
18 R4 | Añadidos |
.getMIMEAsBlob( msgNumber : Integer { ; updateSeen : Boolean } ) : Blob
.getMIMEAsBlob( msgID : Text { ; updateSeen : Boolean } ) : Blob
Parámetros | Tipo | Descripción | |
---|---|---|---|
msgNumber | Integer | -> | Número de secuencia del mensaje |
msgID | Text | -> | ID único del mensaje |
updateSeen | Boolean | -> | Si True, el mensaje se marca como "visto" en el buzón. Si False, el mensaje se deja igual. |
Result | BLOB | <- | 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
Lanzamiento | Modificaciones |
---|---|
17 R5 | Añ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
Lanzamiento | Modificaciones |
---|---|
17 R5 | Añ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:
- SMTP connections - 4DSMTPLog.txt
- POP3 connections - 4DPOP3Log.txt
- IMAP connections - 4DIMAPLog.txt
.move()
Historia
Lanzamiento | Modificaciones |
---|---|
18 R5 | Añadidos |
.move( msgsIDs : Collection ; destinationBox : Text ) : Object
.move( allMsgs : Integer ; destinationBox : Text ) : Object
Parámetros | Tipo | Descripción | |
---|---|---|---|
msgsIDs | Collection | -> | Colección de identificadores únicos de mensajes (cadenas) |
allMsgs | Integer | -> | IMAP all : All messages in the selected mailbox |
destinationBox | Text | -> | Buzón para recibir los mensajes desplazados |
Result | Object | <- | 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:
Propiedad | Tipo | Descripción | |
---|---|---|---|
success | Boolean | True si la operación tiene éxito, False en caso contrario | |
statusText | Text | Mensaje de estado devuelto por el servidor IMAP, o último error devuelto en la pila de errores 4D | |
errors | Collection | Pila de errores 4D (no se devuelve si se recibe una respuesta del servidor IMAP) | |
[].errcode | Number | Código de error 4D | |
[].message | Text | Descripción del error 4D | |
[].componentSignature | Text | Firma 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
Lanzamiento | Modificaciones |
---|---|
18 R5 | Añadidos |
.numToID( startMsg : Integer ; endMsg : Integer ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
startMsg | Integer | -> | Número de secuencia del primer mensaje |
endMsg | Integer | -> | Número de secuencia del último mensaje |
Result | Collection | <- | 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
Lanzamiento | Modificaciones |
---|---|
20 | Soporta palabras claves personalizadas |
18 R6 | Añadidos |
.removeFlags( msgIDs : Collection ; keywords : Object ) : Object
.removeFlags( msgIDs : Text ; keywords : Object ) : Object
.removeFlags( msgIDs : Longint ; keywords : Object ) : Object
Parámetros | Tipo | Descripción | |
---|---|---|---|
msgIDs | Collection | -> | 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 |
keywords | Object | -> | Banderas de palabras claves a eliminar |
Result | Object | <- | 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:
Constante | Valor | Comentario |
---|---|---|
IMAP all | 1 | Seleccionar 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ámetros | Tipo | Descripción |
---|---|---|
$draft | Boolean | True para eliminar el marcador "draft" del mensaje |
$seen | Boolean | True para eliminar el marcador "seen" del mensaje |
$flagged | Boolean | True para eliminar el marcador "flagged" del mensaje |
$answered | Boolean | True para eliminar el marcador "answered" del mensaje |
$deleted | Boolean | True para eliminar el marcador "deleted" del mensaje |
<custom flag> | Boolean | True 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:
Propiedad | Tipo | Descripción | |
---|---|---|---|
success | Boolean | True si la operación tiene éxito, False en caso contrario | |
statusText | Text | Mensaje de estado devuelto por el servidor IMAP, o último error devuelto en la pila de errores 4D | |
errors | Collection | Pila de errores 4D (no se devuelve si se recibe una respuesta del servidor IMAP) | |
[].errcode | Number | Código de error 4D | |
[].message | Text | Descripción del error 4D | |
[].componentSignature | Text | Firma 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
Lanzamiento | Modificaciones |
---|---|
19 | Añadidos |
.renameBox( currentName : Text ; newName : Text ) : Object
Parámetros | Tipo | Descripción | |
---|---|---|---|
currentName | Text | -> | Nombre del nuevo actual |
newName | Text | -> | Nuevo nombre del buzón |
Result | Object | <- | 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:
Propiedad | Tipo | Descripción | |
---|---|---|---|
success | Boolean | True si la operación tiene éxito, False en caso contrario | |
statusText | Text | Mensaje de estado devuelto por el servidor IMAP, o último error devuelto en la pila de errores 4D | |
errors | Collection | Pila de errores 4D (no se devuelve si se recibe una respuesta del servidor IMAP) | |
[].errcode | Number | Código de error 4D | |
[].message | Text | Descripción del error 4D | |
[].componentSignature | Text | Firma 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
Lanzamiento | Modificaciones |
---|---|
17 R4 | Añ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
Lanzamiento | Modificaciones |
---|---|
18 R5 | Añadidos |
.searchMails( searchCriteria : Text ) : Collection
Parámetros | Tipo | Descripción | |
---|---|---|---|
searchCriteria | Text | -> | Criterio de búsqueda |
Result | Collection | <- | 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
orConvert 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:*
is2,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
Lanzamiento | Modificaciones |
---|---|
20 | id, flags, permanentFlags are returned |
18 R4 | Añadidos |
.selectBox( name : Text { ; state : Integer } ) : Object
Parámetros | Tipo | Descripción | |
---|---|---|---|
name | Text | -> | Nombre del buzón |
state | Integer | -> | Estado de acceso al buzón |
Result | Object | <- | 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:
Constante | Valor | Comentario |
---|---|---|
IMAP read only state | 1 | Se 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 state | 0 | Se 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:
Propiedad | Tipo | Descripción |
---|---|---|
name | Text | Nombre del buzón |
mailCount | number | Número de mensajes en el buzón |
mailRecent | number | Número de mensajes con la bandera "recent" |
id | text | Id. único del buzón |
flags | text | Lista de banderas utilizadas actualmente para el buzón, separadas por espacios |
permanentFlags | text | Lista de banderas que el cliente puede cambiar permanentemente (excepto el indicador \Recent, que gestiona el servidor IMAP), separados por espacios |
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
Lanzamiento | Modificaciones |
---|---|
19 | Añadidos |
.subscribe( name : Text ) : Object
Parámetros | Tipo | Descripción | |
---|---|---|---|
name | Text | -> | Nombre del buzón |
Result | Object | <- | 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:
Propiedad | Tipo | Descripción | |
---|---|---|---|
success | Boolean | True si la operación tiene éxito, False en caso contrario | |
statusText | Text | Mensaje de estado devuelto por el servidor IMAP, o último error devuelto en la pila de errores 4D | |
errors | Collection | Pila de errores 4D (no se devuelve si se recibe una respuesta del servidor IMAP) | |
[].errcode | Number | Código de error 4D | |
[].message | Text | Descripción del error 4D | |
[].componentSignature | Text | Firma 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
Lanzamiento | Modificaciones |
---|---|
19 | Añadidos |
.unsubscribe( name : Text ) : Object
Parámetros | Tipo | Descripción | |
---|---|---|---|
name | Text | -> | Nombre del buzón |
Result | Object | <- | 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:
Propiedad | Tipo | Descripción | |
---|---|---|---|
success | Boolean | True si la operación tiene éxito, False en caso contrario | |
statusText | Text | Mensaje de estado devuelto por el servidor IMAP, o último error devuelto en la pila de errores 4D | |
errors | Collection | Pila de errores 4D (no se devuelve si se recibe una respuesta del servidor IMAP) | |
[].errcode | Number | Código de error 4D | |
[].message | Text | Descripción del error 4D | |
[].componentSignature | Text | Firma 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
Lanzamiento | Modificaciones |
---|---|
17 R4 | Añadidos |
.user : Text
Descripción
The .user
property contains the user name used for authentication on the mail server.