IMAPTransporter
The IMAPTransporter
class allows you to retrieve messages from a IMAP email server.
IMAP Transporter object
IMAP Transporter objects are instantiated with the IMAP New transporter command. Eles oferecem as propriedades abaixo e funções:
.acceptUnsecureConnection : Boolean Verdadeiro se 4D for permitido estabelecer uma ligação não encriptada |
.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 o modo de autenticação utilizado para abrir a sessão no servidor de correio |
.checkConnection() : Object verifica a ligação utilizando a informação armazenada no objeto de transporte |
.checkConnectionDelay : Integer the maximum time (in seconds) allowed prior to checking the connection to the server |
.connectionTimeOut : Integer o tempo máximo de espera (em segundos) permitido para estabelecer uma conexão com o servidor |
.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 o nome ou o endereço IP do servidor anfitrião |
.logFile : Text o caminho do arquivo de registo alargado definido (se existir) para a ligação de correio |
.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 o número do porto utilizado para as transações postais |
.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 o nome de usuário utilizado para autenticação no servidor de correio |
IMAP New transporter
Histórico
Versão | Mudanças |
---|---|
v18 R4 | Adicionado |
IMAP New transporter( server : Object ) : 4D.IMAPTransporter
Parâmetros | Tipo | Descrição | |
---|---|---|---|
server | Objeto | -> | Informação de servidor de correio |
Resultados | 4D.IMAPTransporter | <- | IMAP transporter object |
|
Descrição
The IMAP New transporter
command configures a new IMAP connection according to the server parameter and returns a new transporter object. O objeto transporter retornado vai geralmente ser usado para receber emails.
No parâmetro server, passe um objeto contendo as propriedades abaixo:
server | Valor padrão (se omitido) |
---|---|
.acceptUnsecureConnection : Boolean Verdadeiro se 4D for permitido estabelecer uma ligação não encriptada | False |
.accessTokenOAuth2: Text .accessTokenOAuth2: Object Text string or token object representing OAuth2 authorization credentials. Só é usado com OAUTH2 authenticationMode . Se accessTokenOAuth2 for usado mas authenticationMode for omitido, o protocolo OAuth 2 é usado (se permitido pelo servidor). Not returned in IMAP transporter object. | nenhum |
.authenticationMode : Text o modo de autenticação utilizado para abrir a sessão no servidor de correio | o modo de autenticação mais seguro disponível no servidor é usado |
.checkConnectionDelay : Integer the maximum time (in seconds) allowed prior to checking the connection to the server | 300 |
.connectionTimeOut : Integer o tempo máximo de espera (em segundos) permitido para estabelecer uma conexão com o servidor | 30 |
.host : Text o nome ou o endereço IP do servidor anfitrião | obrigatório |
.logFile : Text o caminho do arquivo de registo alargado definido (se existir) para a ligação de correio | nenhum |
.password : Text User password for authentication on the server. Not returned in IMAP transporter object. | nenhum |
.port : Integer o número do porto utilizado para as transações postais | 993 |
.user : Text o nome de usuário utilizado para autenticação no servidor de correio | nenhum |
Warning: Make sure the defined timeout is lower than the server timeout, otherwise the client timeout will be useless.
Resultados
The function returns an IMAP transporter object. Todas as propriedades retornadas sãoapenas leitura.
The IMAP connection is automatically closed when the transporter object is destroyed.
Exemplo
$server:=New object
$server.host:="imap.gmail.com" //Obrigatório
$server.port:=993
$server.user:="4d@gmail.com"
$server.password:="XXXXXXXX"
$server.logFile:="LogTest.txt" //log para salvar na pasta 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 | Descrição | |
---|---|---|---|
server | Objeto | -> | Informação de servidor de correio |
Resultados | 4D.IMAPTransporter | <- | IMAP transporter object |
|
Descrição
A função 4D.IMAPTransporter.new()
creates and returns a new object of the 4D.IMAPTransporter
type. It is identical to the IMAP New transporter
command (shortcut).
.acceptUnsecureConnection
Histórico
Versão | Mudanças |
---|---|
v17 R4 | Adicionado |
.acceptUnsecureConnection : Boolean
Descrição
A propriedade .acceptUnsecureConnection
contém Verdadeiro se 4D for permitido estabelecer uma ligação não encriptada quando a ligação encriptada não é possível.
Contém False se conexões cifradas não forem permitidas, neste caso um erro é retornado quando a conexão criptografada não for possível.
Estão disponíveis portos seguros:
SMTP
- 465: SMTPS
- 587 ou 25: SMTP com atualização STARTTLS se for compat[ivel com o servidor.
IMAP
- 143: IMAP non-encrypted port
- 993: IMAP com atualização STARTTLS se for compatível com o servidor
POP3
- 110: Porta não criptografada POP3
- 995: POP3 com atualização STARTTLS se suportado pelo servidor.
.addFlags()
Histórico
Versão | Mudanças |
---|---|
v18 R6 | Adicionado |
.addFlags( msgIDs : Collection ; keywords : Object ) : Object
.addFlags( msgIDs : Text ; keywords : Object ) : Object
.addFlags( msgIDs : Longint ; keywords : Object ) : Object
Parâmetros | Tipo | Descrição | |
---|---|---|---|
msgIDs | Collection | -> | Collection of strings: Message unique IDs (text) Text: Unique ID of a message Longint (IMAP all): All messages in the selected mailbox |
keywords | Objeto | -> | Keyword flags to add |
Resultados | Objeto | <- | Status of the addFlags operation |
|
Descrição
A função .addFlags()
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 Value Comentário IMAP all 1 Select all messages in the selected mailbox
The keywords
parameter lets you pass an object with keyword values for specific flags to add to msgIDs
. You can pass any of the following keywords:
Parâmetros | Tipo | Descrição |
---|---|---|
$draft | Booleano | True to add the "draft" flag to the message |
$seen | Booleano | True to add the "seen" flag to the message |
$flagged | Booleano | True to add the "flagged" flag to the message |
$answered | Booleano | True to add the "answered" flag to the message |
$deleted | Booleano | True to add the "deleted" flag to the message |
- False values are ignored.
- The interpretation of keyword flags may vary per mail client.
Objeto devolvido
The function returns an object describing the IMAP status:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | Booleano | True if the operation is successful, False otherwise | |
statusText | Text | Status message returned by the IMAP server, or last error returned in the 4D error stack | |
errors | Collection | 4D error stack (not returned if a IMAP server response is received) | |
[].errcode | Número | 4D error code | |
[].message | Text | Description of the 4D error | |
[].componentSignature | Text | Signature of the internal component which returned the error |
Exemplo
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"
// Create transporter
$transporter:=IMAP New transporter($options)
// Select mailbox
$boxInfo:=$transporter.selectBox("INBOX")
// Mark all messages from INBOX as read/seen
$flags:=New object
$flags["$seen"]:=True
$status:=$transporter.addFlags(IMAP all;$flags)
.append()
Histórico
Versão | Mudanças |
---|---|
v18 R6 | Adicionado |
.append( mailObj : Object ; destinationBox : Text ; options : Object ) : Object
Parâmetros | Tipo | Descrição | |
---|---|---|---|
mailObj | Objeto | -> | Objeto Email |
destinationBox | Text | -> | Mailbox to receive Email object |
options | Objeto | -> | Object containing charset info |
Resultados | Objeto | <- | Status of the append operation |
|
Descrição
A função .append()
appends a mailObj
to the destinationBox
.
In the mailObj
parameter, pass an Email object. In the mailObj
parameter, pass an 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. If omitted, the current mailbox is used.
In the optional options
parameter, you can pass an object to define the charset and encoding for specific parts of the email. Propriedades disponiveis:
Propriedade | Tipo | Descrição |
---|---|---|
headerCharset | Text | Charset e codificação usados para as seguintes partes do e-mail: assunto, nomes de arquivos de anexo e atributos de nome de e-mail. Possible values: See possible charsets table below |
bodyCharset | Text | Charset e codificação usados para o conteúdo html e corpo do e-mail. Possible values: See possible charsets table below |
Possible charsets:
Constante | Value | Comentário |
---|---|---|
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 if possible, otherwise UTF-8 & Quoted-printable (default value) |
modo de correio UTF8 na base64 | US-ASCII_UTF8_B64 | headerCharset & bodyCharset: US-ASCII if possible, otherwise UTF-8 & base64 |
Objeto devolvido
The function returns an object describing the IMAP status:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | Booleano | True if the operation is successful, False otherwise | |
statusText | Text | Status message returned by the IMAP server, or last error returned in the 4D error stack | |
errors | Collection | 4D error stack (not returned if a IMAP server response is received) | |
[].errcode | Número | 4D error code | |
[].message | Text | Description of the 4D error | |
[].componentSignature | Text | Signature of the internal component which returned the error |
Exemplo
To save an email in the Drafts mailbox:
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
Histórico
Versão | Mudanças |
---|---|
v17 R4 | Adicionado |
.authenticationMode : Text
Descrição
A propriedade .authenticationMode<
contém o modo de autenticação utilizado para abrir a sessão no servidor de correio.
Por padrão, o modo mais seguro suportado pelo servidor é usado.
Valores possíveis:
Value | Constantes | Comentário |
---|---|---|
CRAM-MD5 | IMAP authentication CRAM MD5 | Autenticação usando o protocolo CRAM-MD5 |
LOGIN | Autenticação do login/acesso | Autenticação usando o protocolo LOGIN |
OAUTH2 | Autenticação IMAP OAUTH2 | Autenticação usando o protocolo OAuth2 |
PLAIN | IMAP authentication plain | Autenticação usando o protocolo PLAIN |
.checkConnection()
Histórico
Versão | Mudanças |
---|---|
v17 R4 | Adicionado |
.checkConnection() : Object
Parâmetros | Tipo | Descrição | |
---|---|---|---|
Resultados | Objeto | <- | Estado da ligação do objecto transportador |
|
Descrição
A função .checkConnection()
verifica a ligação utilizando a informação armazenada no objeto de transporte, recria a ligação, se necessário, e devolve o estado. Esta função permite verificar se os valores fornecidos pelo utilizador são válidos e consistentes.
Objeto devolvido
A função envia um pedido para o servidor de correio e devolve um objecto descrevendo o estado do correio. This object can contain the following properties:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | boolean | Verdadeiro se a verificação for bem sucedida, Falso de outra forma | |
status | number | (apenas SMTP) Código de estado devolvido pelo servidor de correio (0 no caso de um problema não relacionado com o processamento de correio) | |
statusText | text | Mensagem de estado devolvida pelo servidor de correio, ou último erro devolvido na pilha de erros 4D | |
errors | collection | pilha de erros 4D (não devolvida se for recebida uma resposta do servidor de correio) | |
[ ].errCode | number | 4D error code | |
[ ].message | text | Description of the 4D error | |
[ ].componentSignature | text | Signature of the internal component which returned the error |
.checkConnectionDelay
Histórico
Versão | Mudanças |
---|---|
v18 R4 | Adicionado |
.checkConnectionDelay : Integer
Descrição
The .checkConnectionDelay
property contains the maximum time (in seconds) allowed prior to checking the connection to the server. If this time is exceeded between two method calls, the connection to the server will be checked. 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
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.connectionTimeOut : Integer
Descrição
A propriedade .connectionTimeOut
contém o tempo máximo de espera (em segundos) permitido para estabelecer uma conexão com o servidor. Por padrão, se a propriedade não tiver sido definida no objecto servidor (utilizado para criar o objecto transportador com SMTP Novo transportador
, POP3 Novo transportador
, ou IMAP Novo transportador
), o valor é 30.
.copy()
Histórico
Versão | Mudanças |
---|---|
v18 R5 | Adicionado |
.copy( msgsIDs : Collection ; destinationBox : Text ) : Object
.copy( allMsgs : Integer ; destinationBox : Text ) : Object
Parâmetros | Tipo | Descrição | |
---|---|---|---|
msgsIDs | Collection | -> | Collection of message unique IDs (strings) |
allMsgs | Integer | -> | IMAP all : All messages in the selected mailbox |
destinationBox | Text | -> | Mailbox to receive copied messages |
Resultados | Objeto | <- | Status of the copy operation |
|
Descrição
A função .copy()
copies the messages defined by msgsIDs or allMsgs to the destinationBox on the IMAP server.
Pode passar:
- 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 devolvido
The function returns an object describing the IMAP status:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | Booleano | True if the operation is successful, False otherwise | |
statusText | Text | Status message returned by the IMAP server, or last error returned in the 4D error stack | |
errors | Collection | 4D error stack (not returned if a IMAP server response is received) | |
[].errcode | Número | 4D error code | |
[].message | Text | Description of the 4D error | |
[].componentSignature | Text | Signature of the internal component which returned the error |
Exemplo 1
To copy a selection of messages:
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")
Exemplo 2
To copy all messages in the current mailbox:
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()
Histórico
Versão | Mudanças |
---|---|
v19 | Adicionado |
.createBox( name : Text ) : Object
Parâmetros | Tipo | Descrição | |
---|---|---|---|
name | Text | -> | Name of the new mailbox |
Resultados | Objeto | <- | Status of the mailbox creation operation |
|
Descrição
A função .createBox()
creates a mailbox with the given name
. If the IMAP server’s hierarchy separator character appears elsewhere in the mailbox name, the IMAP server will create any parent names needed to create the given mailbox.
In other words, an attempt to create "Projects/IMAP/Doc" on a server in which "/" is the hierarchy separator character will create:
- 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 devolvido
The function returns an object describing the IMAP status:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | Booleano | True if the operation is successful, False otherwise | |
statusText | Text | Status message returned by the IMAP server, or last error returned in the 4D error stack | |
errors | Collection | 4D error stack (not returned if a IMAP server response is received) | |
[].errcode | Número | 4D error code | |
[].message | Text | Description of the 4D error | |
[].componentSignature | Text | Signature of the internal component which returned the error |
Exemplo
To create a new “Invoices” mailbox:
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
.delete()
Histórico
Versão | Mudanças |
---|---|
v18 R5 | Adicionado |
.delete( msgsIDs : Collection ) : Object
.delete( allMsgs : Integer ) : Object
Parâmetros | Tipo | Descrição | |
---|---|---|---|
msgsIDs | Collection | -> | Collection of message unique IDs (strings) |
allMsgs | Integer | -> | IMAP all : All messages in the selected mailbox |
Resultados | Objeto | <- | Status of the delete operation |
|
Descrição
A função .delete()
sets the "deleted" flag for the messages defined in msgsIDs
or allMsgs
.
Pode passar:
- 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.
Executing this function does not actually remove messages. 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 devolvido
The function returns an object describing the IMAP status:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | Booleano | True if the operation is successful, False otherwise | |
statusText | Text | Status message returned by the IMAP server, or last error returned in the 4D error stack | |
errors | Collection | 4D error stack (not returned if a IMAP server response is received) | |
[].errcode | Número | 4D error code | |
[].message | Text | Description of the 4D error | |
[].componentSignature | Text | Signature of the internal component which returned the error |
Exemplo 1
To delete a selection of messages:
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)
Exemplo 2
To delete all messages in the current mailbox:
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()
Histórico
Versão | Mudanças |
---|---|
v19 | Adicionado |
.deleteBox( name : Text ) : Object
Parâmetros | Tipo | Descrição | |
---|---|---|---|
name | Text | -> | Name of the mailbox to delete |
Resultados | Objeto | <- | Status of the mailbox deletion operation |
|
Descrição
A função .deleteBox()
permanently removes the mailbox with the given name
from the IMAP server. Attempting to delete an INBOX or a mailbox that does not exist will generate an error.
In the name
parameter, pass the name of the mailbox to delete.
- The function cannot delete a mailbox that has child mailboxes if the parent mailbox has the "\Noselect" attribute.
- All messages in the deleted mailbox will also be deleted.
- The ability to delete a mailbox depends on the mail server.
Objeto devolvido
The function returns an object describing the IMAP status:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | Booleano | True if the operation is successful, False otherwise | |
statusText | Text | Status message returned by the IMAP server, or last error returned in the 4D error stack | |
errors | Collection | 4D error stack (not returned if a IMAP server response is received) | |
[].errcode | Número | 4D error code | |
[].message | Text | Description of the 4D error | |
[].componentSignature | Text | Signature of the internal component which returned the error |
Exemplo
To delete the "Nova Orion Industries" child mailbox from the "Bills" mailbox hierarchy:
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()
Histórico
Versão | Mudanças |
---|---|
v18 R6 | Adicionado |
.expunge() : Object
Parâmetros | Tipo | Descrição | |
---|---|---|---|
Resultados | Objeto | <- | Status of the expunge operation |
|
Descrição
A função .expunge()
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 devolvido
The function returns an object describing the IMAP status:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | Booleano | True if the operation is successful, False otherwise | |
statusText | Text | Status message returned by the IMAP server, or last error returned in the 4D error stack | |
errors | Collection | 4D error stack (not returned if a IMAP server response is received) | |
[].errcode | Número | 4D error code | |
[].message | Text | Description of the 4D error | |
[].componentSignature | Text | Signature of the internal component which returned the error |
Exemplo
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"
// Create transporter
$transporter:=IMAP New transporter($options)
// Select mailbox
$boxInfo:=$transporter.selectBox("INBOX")
// Find and delete all seen messages in INBOX
$ids:=$transporter.searchMails("SEEN")
$status:=$transporter.delete($ids)
// Purge all messages flagged as deleted
$status:=$transporter.expunge()
.getBoxInfo()
Histórico
Versão | Mudanças |
---|---|
v18 R5 | name is optional |
|v18 R4|Added|
.getBoxInfo( { name : Text }) : Object
Parâmetros | Tipo | Descrição | |
---|---|---|---|
name | Text | -> | Name of the mailbox |
Resultados | Objeto | <- | boxInfo object |
|
Descrição
A função .getBoxInfo()
returns a boxInfo
object corresponding to the current maibox, or the mailbox name. > 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()
.
In the optional name parameter, pass the name of the mailbox to access. The name represents an unambiguous left-to-right hierarchy with levels separated by a specific delimiter character. 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 devolvido
O objeto boxInfo
retornado contém as funcionalidades abaixo:
Propriedade | Tipo | Descrição |
---|---|---|
name | text | Name of the mailbox |
mailCount | number | Número de mensagens na caixa de email |
mailRecent | number | Number of messages with the "recent" flag (indicating new messages) |
Exemplo
var $transporter : 4D.IMAPTransporter
$transporter:=IMAP New transporter($server)
$info:=$transporter.getBoxInfo("INBOX")
ALERT("INBOX contains "+String($info.mailRecent)+" recent emails.")
.getBoxList()
Histórico
Versão | Mudanças |
---|---|
v18 R4 | Adicionado |
v19 | Add isSubscribed parameter |
.getBoxList( { parameters : Object } ) : Collection
Parâmetros | Tipo | Descrição | |
---|---|---|---|
parameters | Objeto | -> | Parameter object |
Resultados | Collection | <- | Collection of mailbox objects |
|
Descrição
A função .getBoxList()
returns a collection of mailboxes describing all of the available mailboxes. This function allows you to locally manage the list of messages located on the IMAP mail server.
In the optional parameters
parameter, pass an object containing values to filter the returned mailboxes. Pode passar:
Propriedade | Tipo | Descrição |
---|---|---|
isSubscribed | Booleano |
Resultados
Each object of the returned collection contains the following properties:
Propriedade | Tipo | Descrição |
---|---|---|
[].name | text | Name of the mailbox |
[].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:
|
If the account does not contain any mailboxes, an empty collection is returned.
- 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.
Exemplo
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()
Histórico
Versão | Mudanças |
---|---|
v18 R4 | Adicionado |
.getDelimiter() : Text
Parâmetros | Tipo | Descrição | |
---|---|---|---|
Resultados | Text | <- | Hierarchy delimiter character |
|
Descrição
A função .getDelimiter()
returns the character used to delimit levels of hierarchy in the mailbox name.
The delimiter is a character which can be used to:
- create lower level (inferior) mailboxes
- search higher or lower within the mailbox hierarchy
Resultados
Mailbox name delimiter character.
- 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.
Exemplo
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()
Histórico
Versão | Mudanças |
---|---|
v18 R4 | Adicionado |
.getMail( msgNumber: Integer { ; options : Object } ) : Object
.getMail( msgID: Text { ; options : Object } ) : Object
Parâmetros | Tipo | Descrição | |
---|---|---|---|
msgNumber | Integer | -> | Sequence number of the message |
msgID | Text | -> | ID única da mensagem |
options | Objeto | -> | Message handling instructions |
Resultados | Objeto | <- | Email object |
|
Descrição
A função .getMail()
returns the Email
object corresponding to the msgNumber or msgID in the mailbox designated by the IMAP_transporter
. Essa função permite manejar localmente os conteúdos de email.
In the first parameter, you can pass either:
- 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. As seguintes propriedades estão disponíveis:
Propriedade | Tipo | Descrição |
---|---|---|
updateSeen | boolean | If True, the message is marked as "seen" in the mailbox. If False, the message is not marked as "seen". Default value: True |
withBody | boolean | Pass True to return the body of the message. If False, only the message header is returned. Default value: 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()
`.
Resultados
.getMail()
returns an Email
object with the following specific IMAP properties: id, receivedAt, and size.
Exemplo
You want to get the message with 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()
Histórico
Versão | Mudanças |
---|---|
v18 R5 | Adicionado |
.getMails( ids : Collection { ; options : Object } ) : Object
.getMails( startMsg : Integer ; endMsg : Integer { ; options : Object } ) : Object
Parâmetros | Tipo | Descrição | |
---|---|---|---|
ids | Collection | -> | Collection of message ID |
startMsg | Integer | -> | Sequence number of the first message |
endMsg | Integer | -> | Sequence number of the last message |
options | Objeto | -> | Message handling instructions |
Resultados | Objeto | <- | Object containing:
|
|
Descrição
A função .getMails()
returns an object containing a collection of Email
objects.
First Syntax:
.getMails( ids { ; options } ) -> result
The first syntax allows you to retrieve messages based on their IDs.
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.
Second syntax:
.getMails( startMsg ; endMsg { ; options } ) -> result
The second syntax allows you to retrieve messages based on a sequential range. The values passed represent the position of the messages in the 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.
The optional options parameter allows you to define the parts of the messages to be returned.
Options
Propriedade | Tipo | Descrição |
---|---|---|
updateSeen | Booleano | If True, the specified messages are marked as "seen" in the mailbox. If False, the messages are not marked as "seen". Default value: True |
withBody | Booleano | Pass True to return the body of the specified messages. If False, only the message headers are returned. Default value: 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()
.
Resultados
.getMails()
returns an object containing the following collections:
Propriedade | Tipo | Descrição |
---|---|---|
lista | Collection | Collection of Email objects. If no Email objects are found, an empty collection is returned. |
notFound | Collection | Collection of:
|
Exemplo
You want to retrieve the 20 most recent emails without changing their "seen" status:
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 if
.getMIMEAsBlob()
Histórico
Versão | Mudanças |
---|---|
v18 R4 | Adicionado |
.getMIMEAsBlob( msgNumber : Integer { ; updateSeen : Boolean } ) : Blob
.getMIMEAsBlob( msgID : Text { ; updateSeen : Boolean } ) : Blob
Parâmetros | Tipo | Descrição | |
---|---|---|---|
msgNumber | Integer | -> | Sequence number of the message |
msgID | Text | -> | ID única da mensagem |
updateSeen | Booleano | -> | If True, the message is marked "seen" in the mailbox. If False the message is left untouched. |
Resultados | BLOB | <- | Blob of the MIME string returned from the mail server |
|
Descrição
A função .getMIMEAsBlob()
returns a BLOB containing the MIME contents for the message corresponding to the msgNumber or msgID in the mailbox designated by the IMAP_transporter
.
In the first parameter, you can pass either:
- 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. Pode passar:
- 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()
.- 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()
.
Resultados
.getMIMEAsBlob()
retorna um BLOB
que pode ser arquivado em um banco de dados ou convertido a um objeto Email
com o comando MAIL Convert from MIME
.
Exemplo
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
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.host : Text
Descrição
A propriedade .host
contém o nome ou o endereço IP do servidor anfitrião. Utilizado para transacções postais (SMTP, POP3, IMAP).
.logFile
Histórico
Versão | Mudanças |
---|---|
v17 R5 | Adicionado |
.logFile : Text
Descrição
A propriedade .logFile
contém o caminho do arquivo de registo alargado definido (se existir) para a ligação de correio. Pode ser relativo (à pasta atual de Logs) ou absoluto.
Ao contrário dos arquivos de registo regulares (ativados através do comando SET DATABASE PARAMETER
), os arquivos de registo armazenam o conteúdo MIME de todos os e-mails enviados e não têm qualquer limite de tamanho. Para mais informações sobre arquivos de registo estendidos, consultar:
- Conexões SMTP - 4DSMTPLog.txt
- Conexões POP3 - 4DPOP3Log.txt
- Conexões IMAP - 4DIMAPLog.txt
.move()
Histórico
Versão | Mudanças |
---|---|
v18 R5 | Adicionado |
.move( msgsIDs : Collection ; destinationBox : Text ) : Object
.move( allMsgs : Integer ; destinationBox : Text ) : Object
Parâmetros | Tipo | Descrição | |
---|---|---|---|
msgsIDs | Collection | -> | Collection of message unique IDs (strings) |
allMsgs | Integer | -> | IMAP all : All messages in the selected mailbox |
destinationBox | Text | -> | Mailbox to receive moved messages |
Resultados | Objeto | <- | Status of the move operation |
|
Descrição
A função .move()
moves the messages defined by msgsIDs or allMsgs to the destinationBox on the IMAP server.
Pode passar:
- 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 devolvido
The function returns an object describing the IMAP status:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | Booleano | True if the operation is successful, False otherwise | |
statusText | Text | Status message returned by the IMAP server, or last error returned in the 4D error stack | |
errors | Collection | 4D error stack (not returned if a IMAP server response is received) | |
[].errcode | Número | 4D error code | |
[].message | Text | Description of the 4D error | |
[].componentSignature | Text | Signature of the internal component which returned the error |
Exemplo 1
To move a selection of messages:
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")
Exemplo 2
To move all messages in the current mailbox:
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()
Histórico
Versão | Mudanças |
---|---|
v18 R5 | Adicionado |
.numToID( startMsg : Integer ; endMsg : Integer ) : Collection
Parâmetros | Tipo | Descrição | |
---|---|---|---|
startMsg | Integer | -> | Sequence number of the first message |
endMsg | Integer | -> | Sequence number of the last message |
Resultados | Collection | <- | Collection of unique IDs |
|
Descrição
A função .numToID()
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.
Resultados
The function returns a collection of strings (unique IDs).
Exemplo
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()
Histórico
Versão | Mudanças |
---|---|
v18 R6 | Adicionado |
.removeFlags( msgIDs : Collection ; keywords : Object ) : Object
.removeFlags( msgIDs : Text ; keywords : Object ) : Object
.removeFlags( msgIDs : Longint ; keywords : Object ) : Object
Parâmetros | Tipo | Descrição | |
---|---|---|---|
msgIDs | Collection | -> | Collection of strings: Message unique IDs (text) Text: Unique ID of a message Longint (IMAP all): All messages in the selected mailbox |
keywords | Objeto | -> | Keyword flags to remove |
Resultados | Objeto | <- | Status of the removeFlags operation |
|
Descrição
A função .removeFlags()
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 Value Comentário IMAP all 1 Select all messages in the selected mailbox
The keywords
parameter lets you pass an object with keyword values for specific flags to remove from msgIDs
. You can pass any of the following keywords:
Parâmetros | Tipo | Descrição |
---|---|---|
$draft | Booleano | True to remove the "draft" flag from the message |
$seen | Booleano | True to remove the "seen" flag from the message |
$flagged | Booleano | True to remove the "flagged" flag from the message |
$answered | Booleano | True to remove the "answered" flag from the message |
$deleted | Booleano | True to remove the "deleted" flag from the message |
Note that False values are ignored.
Objeto devolvido
The function returns an object describing the IMAP status:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | Booleano | True if the operation is successful, False otherwise | |
statusText | Text | Status message returned by the IMAP server, or last error returned in the 4D error stack | |
errors | Collection | 4D error stack (not returned if a IMAP server response is received) | |
[].errcode | Número | 4D error code | |
[].message | Text | Description of the 4D error | |
[].componentSignature | Text | Signature of the internal component which returned the error |
Exemplo
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"
// Create transporter
$transporter:=IMAP New transporter($options)
// Select mailbox
$boxInfo:=$transporter.selectBox("INBOX")
// Mark all messages from INBOX as unseen
$flags:=New object
$flags["$seen"]:=True
$status:=$transporter.removeFlags(IMAP all;$flags)
.renameBox()
Histórico
Versão | Mudanças |
---|---|
v19 | Adicionado |
.renameBox( currentName : Text ; newName : Text ) : Object
Parâmetros | Tipo | Descrição | |
---|---|---|---|
currentName | Text | -> | Name of the current mailbox |
newName | Text | -> | New mailbox name |
Resultados | Objeto | <- | Status of the renaming operation |
|
Descrição
A função .renameBox()
changes the name of a mailbox on the IMAP server. Attempting to rename a mailbox from a mailbox name that does not exist or to a mailbox name that already exists will generate an 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 devolvido
The function returns an object describing the IMAP status:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | Booleano | True if the operation is successful, False otherwise | |
statusText | Text | Status message returned by the IMAP server, or last error returned in the 4D error stack | |
errors | Collection | 4D error stack (not returned if a IMAP server response is received) | |
[].errcode | Número | 4D error code | |
[].message | Text | Description of the 4D error | |
[].componentSignature | Text | Signature of the internal component which returned the error |
Exemplo
To to rename your “Invoices” mailbox to “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
Histórico
Versão | Mudanças |
---|---|
v17 R4 | Adicionado |
.port : Integer
Descrição
A propriedade .port
contém o número do porto utilizado para as transações postais. Por padrão, se a propriedade não tiver sido definida no objeto servidor (utilizado para criar o objecto transportador com SMTP Novo transportador
, POP3 Novo transportador
, ou IMAP Novo transportador
), o valor é 30:
- SMTP - 587
- POP3 - 995
- IMAP - 993
.searchMails()
Histórico
Versão | Mudanças |
---|---|
v18 R5 | Adicionado |
.searchMails( searchCriteria : Text ) : Collection
Parâmetros | Tipo | Descrição | |
---|---|---|---|
searchCriteria | Text | -> | Critérios de pesquisa |
Resultados | Collection | <- | Collection of message numbers |
|
Descrição
This function is based upon the specification for the IMAP protocol.
A função .searchMails()
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. A search key may be a single or multiple items. Por exemplo:
SearchKey1 = FLAGGED SearchKey2 = NOT FLAGGED SearchKey3 = FLAGGED DRAFT
Matching is usually not case-sensitive
- 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
... returns all messages with \Seen flag set OR \Flagged flag set
searchCriteria = NOT SEEN
... returns all messages with \Seen flag not set.
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 ”.
As concerns the last two examples, notice that the result of the search is different when you remove the parentheses of the first search key list.
- The searchCriteria may include the optional [CHARSET] specification. This consists of the "CHARSET" word followed by a registered [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). By default, 4D encodes in Quotable Printable the searchCriteria string if it contains extended characters.
searchCriteria = CHARSET "ISO-8859" BODY "Help"
... means the search criteria uses the charset iso-8859 and the server will have to convert the search criteria before searching, if necessary.
Search value types
Search-keys may request the value to search for:
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. If the string does not contain any special characters, like the space character for instance, it does not need to be quoted. Quoting such strings will ensure that your string value will be correctly interpreted. 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. Matching is not case-sensitive.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. For message sequence numbers, these are consecutive numbers from 1 to the total number of messages in the mailbox. A comma delimits individual numbers; a colon delimits between two numbers 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.
Authorized search-keys
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()
Histórico
Versão | Mudanças |
---|---|
v18 R4 | Adicionado |
.selectBox( name : Text { ; state : Integer } ) : Object
Parâmetros | Tipo | Descrição | |
---|---|---|---|
name | Text | -> | Name of the mailbox |
state | Integer | -> | Mailbox access status |
Resultados | Objeto | <- | boxInfo object |
|
Descrição
A função .selectBox()
selects the name mailbox as the current mailbox. Essa função permite que recupere informação sobre o mailbox.
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. The name represents an unambiguous left-to-right hierarchy with levels separated by a specific delimiter character. The delimiter can be found with the .getDelimiter()
function.
The optional state parameter defines the type of access to the mailbox. The possible values are:
Constante | Value | Comentário |
---|---|---|
IMAP read only state | 1 | The selected mailbox is accessed with read only privileges. Messages with a "recent" flag (indicating new messages) remain unchanged. |
IMAP read write state | 0 | The selected mailbox is accessed with read and write privileges. Messages are considered "seen" and lose the "recent" flag (indicating new messages). (Valor padrão) |
- 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 devolvido
O objeto boxInfo
retornado contém as funcionalidades abaixo:
Propriedade | Tipo | Descrição |
---|---|---|
name | Text | Name of the mailbox |
mailCount | number | Número de mensagens na caixa de email |
mailRecent | number | Number of messages with the "recent" flag |
Exemplo
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()
Histórico
Versão | Mudanças |
---|---|
v19 | Adicionado |
.subscribe( name : Text ) : Object
Parâmetros | Tipo | Descrição | |
---|---|---|---|
name | Text | -> | Name of the mailbox |
Resultados | Objeto | <- | Status of the subscribe operation |
|
Descrição
A função .subscribe()
allows adding or removing of the specified mailbox to/from the IMAP server’s set of “subscribed” mailboxes. As such, you can choose to narrow down a large list of available mailboxes by subscribing to those you usually want to see.
In the name
parameter, pass the name of the mailbox to add (subscribe) to your "subscribed" mailboxes.
Objeto devolvido
The function returns an object describing the IMAP status:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | Booleano | True if the operation is successful, False otherwise | |
statusText | Text | Status message returned by the IMAP server, or last error returned in the 4D error stack | |
errors | Collection | 4D error stack (not returned if a IMAP server response is received) | |
[].errcode | Número | 4D error code | |
[].message | Text | Description of the 4D error | |
[].componentSignature | Text | Signature of the internal component which returned the error |
Exemplo
To subscribe to the "Atlas Corp” mailbox in the "Bills" hierarchy:
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
Else
ALERT("Error: "+$status.statusText)
End if
End if
.unsubscribe()
Histórico
Versão | Mudanças |
---|---|
v19 | Adicionado |
.unsubscribe( name : Text ) : Object
Parâmetros | Tipo | Descrição | |
---|---|---|---|
name | Text | -> | Name of the mailbox |
Resultados | Objeto | <- | Status of the unsubscribe operation |
|
Descrição
A função .unsubscribe()
removes a mailbox from a set of subscribed mailboxes. This allows you reduce the number of mailboxes you usually see.
In the name
parameter, pass the name of the mailbox to remove (unsubscribe) from your active mailboxes.
Objeto devolvido
The function returns an object describing the IMAP status:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | Booleano | True if the operation is successful, False otherwise | |
statusText | Text | Status message returned by the IMAP server, or last error returned in the 4D error stack | |
errors | Collection | 4D error stack (not returned if a IMAP server response is received) | |
[].errcode | Número | 4D error code | |
[].message | Text | Description of the 4D error | |
[].componentSignature | Text | Signature of the internal component which returned the error |
Exemplo
To unsubscribe from the "Atlas Corp” mailbox in the "Bills" hierarchy:
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
Else
ALERT("Error: "+$status.statusText)
End if
End if
.user
Histórico
Versão | Mudanças |
---|---|
v17 R4 | Adicionado |
.user : Text
Descrição
A propriedade .user
contém o nome de usuário utilizado para autenticação no servidor de correio.