IMAPTransporter
The IMAPTransporter
class allows you to retrieve messages from a IMAP email server.
Objecto do IMAP Transporter
IMAP Transporter objects are instantiated with the IMAP New transporter command. Eles oferecem as propriedades abaixo e funções:
.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
História
Release | Mudanças |
---|---|
18 R4 | Adicionado |
IMAP New transporter( server : Object ) : 4D.IMAPTransporter
Parâmetro | Tipo | Descrição | |
---|---|---|---|
server | Object | -> | 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.
In the server parameter, pass an object containing the following properties:
server | Valor padrão (se omitido) |
---|---|
.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. | nenhum |
.authenticationMode : Text the authentication mode used to open the session on the mail server | 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 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 | mandatory |
.logFile : Text the path of the extended log file defined (if any) for the mail connection | nenhum |
.password : Text User password for authentication on the server. Not returned in IMAP transporter object. | nenhum |
.port : Integer the port number used for mail transactions | 993 |
.user : Text the user name used for authentication on the mail server | 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. All returned properties are read-only.
A ligação IMAP é automaticamente fechada quando o objecto transportador é destruído.
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âmetro | Tipo | Descrição | |
---|---|---|---|
server | Object | -> | Informação de servidor de correio |
Resultados | 4D.IMAPTransporter | <- | IMAP transporter object |
Descrição
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
História
Release | Mudanças |
---|---|
17 R4 | Adicionado |
.acceptUnsecureConnection : Boolean
Descrição
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.
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ória
Release | Mudanças |
---|---|
20 | Suporta palavras-chave personalizadas |
18 R6 | Adicionado |
.addFlags( msgIDs : Collection ; keywords : Object ) : Object
.addFlags( msgIDs : Text ; keywords : Object ) : Object
.addFlags( msgIDs : Longint ; keywords : Object ) : Object
Parâmetro | Tipo | Descrição | |
---|---|---|---|
msgIDs | Collection | -> | Coleção de strings: IDs únicos de mensagens (texto) Texto: ID único de uma mensagem Longint (todos IMAP): Todas as mensagens na caixa de correio seleccionada |
keywords | Object | -> | Flags de palavras chaves a adicionar |
Resultados | Object | <- | Estado da operação addFlags |
Descrição
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:
Parâmetros | Valor | Comentário |
---|---|---|
IMAP all | 1 | Seleccione todas as mensagens na caixa de correio seleccionada |
The keywords
parameter lets you define the flags to add to msgIDs
. Pode passar qualquer uma das seguintes palavras-chave:
Propriedade | Tipo | Descrição |
---|---|---|
$draft | Parâmetros | True para adicionar o marcador "draft" na mensagem |
$seen | Parâmetros | True para adicionar o marcador "seen" na mensagem |
$flagged | Parâmetros | True para adicionar o marcador "flagged" na mensagem |
$answered | Parâmetros | True para adicionar o marcador "answered" na mensagem |
$deleted | Parâmetros | True para adicionar o marcador "deleted" na mensagem |
<custom flag> | Parâmetros | True para adicionar o marcador personalizado na mensagem |
Os nomes das bandeiras personalizadas devem respeitar esta regra: a palavra-chave deve ser um fio não sensível a maiúsculas e minúsculas, excluindo caracteres de controlo e espaço, e não pode incluir nenhum destes caracteres: ( ) { ] % * " \
- Para que uma palavra-chave seja tida em conta, tem de ser true.
- A interpretação dos marcadores de palavras-chave pode variar por cliente de correio.
Returned object
A função devolve um objecto que descreve o estado IMAP:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | Parâmetros | Verdadeiro se a operação for bem sucedida, Falso caso contrário | |
statusText | Text | Mensagem de estado devolvida pelo servidor IMAP, 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 IMAP) | |
[].errcode | Number | Código de erro 4D | |
[].message | Text | Descrição do erro 4D | |
[].componentSignature | Text | Assinatura da componente interna que devolveu o erro |
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"
// Criar transporter
$transporter:=IMAP New transporter($options)
// Selecionar mailbox
$boxInfo:=$transporter.selectBox("INBOX")
// Marcar todas as mensagens de INBOX como lidas
$flags:=New object
$flags["$seen"]:=True
$status:=$transporter.addFlags(IMAP all;$flags)
.append()
História
Release | Mudanças |
---|---|
18 R6 | Adicionado |
.append( mailObj : Object ; destinationBox : Text ; options : Object ) : Object
Parâmetro | Tipo | Descrição | |
---|---|---|---|
mailObj | Object | -> | Objeto Email |
destinationBox | Text | -> | Caixa de email que vai receber o objeto Email |
options | Object | -> | Objeto que contém informações do charset |
Resultados | Object | <- | Estado da operação anexada |
Descrição
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. Se omitido, é utilizada a caixa de correio actual.
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. Possíveis valores: Ver tabela de possíveis cartas abaixo |
bodyCharset | Text | Charset e codificação usados para o conteúdo html e corpo do e-mail. Possíveis valores: Ver tabela de possíveis cartas abaixo |
Charsets possíveis:
Parâmetros | Valor | 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 se possível, caso contrário UTF-8 & Quoted-printable (valor padrão) |
modo de correio UTF8 na base64 | US-ASCII_UTF8_B64 | headerCharset & bodyCharset: US-ASCII se possível, caso contrário UTF-8 & base64 |
Returned object
A função devolve um objecto que descreve o estado IMAP:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | Parâmetros | Verdadeiro se a operação for bem sucedida, Falso caso contrário | |
statusText | Text | Mensagem de estado devolvida pelo servidor IMAP, 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 IMAP) | |
[].errcode | Number | Código de erro 4D | |
[].message | Text | Descrição do erro 4D | |
[].componentSignature | Text | Assinatura da componente interna que devolveu o erro |
Exemplo
Para guardar um e-mail na caixa de correio Drafts:
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ória
Release | Mudanças |
---|---|
17 R4 | Adicionado |
.authenticationMode : Text
Descrição
The .authenticationMode
property contains the authentication mode used to open the session on the mail server.
Por padrão, o modo mais seguro suportado pelo servidor é usado.
Valores possíveis:
Valor | Constantes | Comentário |
---|---|---|
CRAM-MD5 | IMAP authentication CRAM MD5 | Autenticação usando o protocolo CRAM-MD5 |
LOGIN | IMAP authentication login | 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ória
Release | Mudanças |
---|---|
17 R4 | Adicionado |
.checkConnection() : Object
Parâmetro | Tipo | Descrição | |
---|---|---|---|
Resultados | Object | <- | Estado da ligação do objecto transportador |
Descrição
The .checkConnection()
function checks the connection using information stored in the transporter object, recreates the connection if necessary, and returns the status. 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. Este objeto pode conter as seguintes propriedades:
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 | Código de erro 4D | |
[ ].message | text | Descrição do erro 4D | |
[ ].componentSignature | text | Assinatura da componente interna que devolveu o erro |
.checkConnectionDelay
História
Release | Mudanças |
---|---|
18 R4 | Adicionado |
.checkConnectionDelay : Integer
Descrição
The .checkConnectionDelay
property contains the maximum time (in seconds) allowed prior to checking the connection to the server. Se este tempo for excedido entre duas chamadas de método, a ligação ao servidor será verificada. 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ória
Release | Mudanças |
---|---|
17 R5 | Adicionado |
.connectionTimeOut : Integer
Descrição
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()
História
Release | Mudanças |
---|---|
18 R5 | Adicionado |
.copy( msgsIDs : Collection ; destinationBox : Text ) : Object
.copy( allMsgs : Integer ; destinationBox : Text ) : Object
Parâmetro | Tipo | Descrição | |
---|---|---|---|
msgsIDs | Collection | -> | Coleção de identificadores únicos de mensagens (strings) |
allMsgs | Integer | -> | IMAP all : All messages in the selected mailbox |
destinationBox | Text | -> | Caixa de correio para receber mensagens copiadas |
Resultados | Object | <- | Estado da operação anexada |
Descrição
The .copy()
function 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.
Returned object
A função devolve um objecto que descreve o estado IMAP:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | Parâmetros | Verdadeiro se a operação for bem sucedida, Falso caso contrário | |
statusText | Text | Mensagem de estado devolvida pelo servidor IMAP, 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 IMAP) | |
[].errcode | Number | Código de erro 4D | |
[].message | Text | Descrição do erro 4D | |
[].componentSignature | Text | Assinatura da componente interna que devolveu o erro |
Exemplo 1
Para copiar uma selecção de mensagens:
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
Para copiar todas as mensagens na caixa de correio 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()
História
Release | Mudanças |
---|---|
19 | Adicionado |
.createBox( name : Text ) : Object
Parâmetro | Tipo | Descrição | |
---|---|---|---|
name | Text | -> | Nome da nova caixa de correio |
Resultados | Object | <- | Estado da operação de criação da caixa de correio |
Descrição
The .createBox()
function creates a mailbox with the given name
. Se o carácter separador hierárquico do servidor IMAP aparecer noutro lugar no nome da caixa de correio, o servidor IMAP criará os nomes dos pais necessários para criar a caixa de correio em questão.
Por outras palavras, uma tentativa de criar "Projectos/IMAP/Doc" num servidor em que "/" é o carácter separador hierárquico criará:
- 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.
Returned object
A função devolve um objecto que descreve o estado IMAP:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | Parâmetros | Verdadeiro se a operação for bem sucedida, Falso caso contrário | |
statusText | Text | Mensagem de estado devolvida pelo servidor IMAP, 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 IMAP) | |
[].errcode | Number | Código de erro 4D | |
[].message | Text | Descrição do erro 4D | |
[].componentSignature | Text | Assinatura da componente interna que devolveu o erro |
Exemplo
Para criar uma nova caixa de correio "Facturas":
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()
História
Release | Mudanças |
---|---|
18 R5 | Adicionado |
.delete( msgsIDs : Collection ) : Object
.delete( allMsgs : Integer ) : Object
Parâmetro | Tipo | Descrição | |
---|---|---|---|
msgsIDs | Collection | -> | Coleção de identificadores únicos de mensagens (strings) |
allMsgs | Integer | -> | IMAP all : All messages in the selected mailbox |
Resultados | Object | <- | Estado da operação apagada |
Descrição
The .delete()
function 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.
A execução desta função não remove realmente as mensagens. 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.
Returned object
A função devolve um objecto que descreve o estado IMAP:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | Parâmetros | Verdadeiro se a operação for bem sucedida, Falso caso contrário | |
statusText | Text | Mensagem de estado devolvida pelo servidor IMAP, 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 IMAP) | |
[].errcode | Number | Código de erro 4D | |
[].message | Text | Descrição do erro 4D | |
[].componentSignature | Text | Assinatura da componente interna que devolveu o erro |
Exemplo 1
Para apagar uma selecção de mensagens:
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
Para apagar todas as mensagens na caixa de correio 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()
História
Release | Mudanças |
---|---|
19 | Adicionado |
.deleteBox( name : Text ) : Object
Parâmetro | Tipo | Descrição | |
---|---|---|---|
name | Text | -> | Nome da caixa de correio a apagar |
Resultados | Object | <- | Estado da operação de eliminação da caixa de correio |
Descrição
The .deleteBox()
function permanently removes the mailbox with the given name
from the IMAP server. A tentativa de apagar uma INBOX ou uma caixa de correio que não existe, gerará um erro.
In the name
parameter, pass the name of the mailbox to delete.
- A função não pode apagar uma caixa de correio que tenha caixas de correio para crianças se a caixa de correio dos pais tiver o atributo "\Noselect".
- Todas as mensagens na caixa de correio eliminadas serão também eliminadas.
- A capacidade de apagar uma caixa de correio depende do servidor de correio.
Returned object
A função devolve um objecto que descreve o estado IMAP:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | Parâmetros | Verdadeiro se a operação for bem sucedida, Falso caso contrário | |
statusText | Text | Mensagem de estado devolvida pelo servidor IMAP, 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 IMAP) | |
[].errcode | Number | Código de erro 4D | |
[].message | Text | Descrição do erro 4D | |
[].componentSignature | Text | Assinatura da componente interna que devolveu o erro |
Exemplo
Para eliminar a caixa de correio filha "Nova Orion Industries" da hierarquia da caixa de correio "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()
História
Release | Mudanças |
---|---|
18 R6 | Adicionado |
.expunge() : Object
Parâmetro | Tipo | Descrição | |
---|---|---|---|
Resultados | Object | <- | Estado da operação de expurgo |
Descrição
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.
Returned object
A função devolve um objecto que descreve o estado IMAP:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | Parâmetros | Verdadeiro se a operação for bem sucedida, Falso caso contrário | |
statusText | Text | Mensagem de estado devolvida pelo servidor IMAP, 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 IMAP) | |
[].errcode | Number | Código de erro 4D | |
[].message | Text | Descrição do erro 4D | |
[].componentSignature | Text | Assinatura da componente interna que devolveu o erro |
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"
// Criar transporter
$transporter:=IMAP New transporter($options)
// Selecionar mailbox
$boxInfo:=$transporter.selectBox("INBOX")
// Encontrar e apagar todas as mensagens vistas no INBOX
$ids:=$transporter.searchMails("SEEN")
$status:=$transporter.delete($ids)
// Expurga todas as mensagens marcadas como apagadas
$status:=$transporter.expunge()
.getBoxInfo()
História
Release | Mudanças |
---|---|
20 | id is returned |
18 R5 | name is optional |
18 R4 | Adicionado |
.getBoxInfo( { name : Text }) : Object
Parâmetro | Tipo | Descrição | |
---|---|---|---|
name | Text | -> | Nome da nova caixa de correio |
Resultados | Object | <- | objecto boxInfo |
Descrição
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. O nome representa uma hierarquia inequívoca da esquerda para a direita com níveis separados por um 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.
Returned object
The boxInfo
object returned contains the following properties:
Propriedade | Tipo | Descrição |
---|---|---|
name | text | Nome da nova caixa de correio |
mailCount | number | Número de mensagens na caixa de email |
mailRecent | number | Número de mensagens com o marcador "recente" (indicando novas mensagens) |
id | text | Parâmetros |
Exemplo
var $transporter : 4D.IMAPTransporter
$transporter:=IMAP New transporter($server)
$info:=$transporter.getBoxInfo("INBOX")
ALERT("INBOX contains "+String($info.mailRecent)+" recent emails.")
.getBoxList()
História
Release | Mudanças |
---|---|
18 R4 | Adicionado |
19 | Add isSubscribed parameter |
.getBoxList( { parameters : Object } ) : Collection
Parâmetro | Tipo | Descrição | |
---|---|---|---|
parameters | Object | -> | Parâmetros |
Resultados | Collection | <- | Coleção de objetos da caixa de correio |
Descrição
The .getBoxList()
function returns a collection of mailboxes describing all of the available mailboxes. Esta função permite gerir localmente a lista de mensagens localizadas no servidor de correio IMAP.
In the optional parameters
parameter, pass an object containing values to filter the returned mailboxes. Pode passar:
Propriedade | Tipo | Descrição |
---|---|---|
isSubscribed | Parâmetros |
Resultados
Cada objecto da coleção devolvida contém as seguintes propriedades:
Propriedade | Tipo | Descrição |
---|---|---|
[].name | text | Nome da nova caixa de correio |
[].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:
|
Se a conta não contiver quaisquer caixas de correio, é devolvida uma colecção vazia.
- 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ória
Release | Mudanças |
---|---|
18 R4 | Adicionado |
.getDelimiter() : Text
Parâmetro | Tipo | Descrição | |
---|---|---|---|
Resultados | Text | <- | Hierarchy delimiter character |
Descrição
The .getDelimiter()
function returns the character used to delimit levels of hierarchy in the mailbox name.
O delimitador é um caractere a que se pode usar para:
- criar caixas de correio de nível inferior
- pesquisar hierarquias de nível mais alto ou mais baixo dentro das caixa de correio
Resultados
Carácter delimitador do nome da caixa de correio.
- 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ória
Release | Mudanças |
---|---|
18 R4 | Adicionado |
.getMail( msgNumber: Integer { ; options : Object } ) : Object
.getMail( msgID: Text { ; options : Object } ) : Object
Parâmetro | Tipo | Descrição | |
---|---|---|---|
msgNumber | Integer | -> | Número sequencial da mensagem |
msgID | Text | -> | ID única da mensagem |
options | Object | -> | Instruções de tratamento de mensagens |
Resultados | Object | <- | Email object |
Descrição
The .getMail()
function 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.
No primeiro parâmetro, pode passar qualquer um dos dois:
- 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 | Se Verdadeiro, a mensagem é marcada como "visto" na caixa de correio. Se falso, a mensagem não é marcada como "visto". Valor padrão: True |
withBody | boolean | Pass True para devolver o corpo da mensagem. Se falso, apenas o cabeçalho da mensagem é devolvido. Valor padrão: 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
Se quiser receber uma mensagem com 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ória
Release | Mudanças |
---|---|
18 R5 | Adicionado |
.getMails( ids : Collection { ; options : Object } ) : Object
.getMails( startMsg : Integer ; endMsg : Integer { ; options : Object } ) : Object
Parâmetro | Tipo | Descrição | |
---|---|---|---|
ids | Collection | -> | Colecção de identificação da mensagem |
startMsg | Integer | -> | Número sequencial da primeira mensagem |
endMsg | Integer | -> | Número sequencial da última mensagem |
options | Object | -> | Instruções de tratamento de mensagens |
Resultados | Object | <- | Object containing:
|
Descrição
The .getMails()
function returns an object containing a collection of Email
objects.
First Syntax:
.getMails( ids { ; options } ) -> result
A primeira sintaxe permite recuperar mensagens com base nas suas identificações.
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
A segunda sintaxe permite recuperar mensagens com base num intervalo sequencial. Os valores passados representam a posição das mensagens na caixa de correio.
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 | Parâmetros | Se Verdadeiro, as mensagens especificadas são marcadas como "vistas" na caixa de correio. Se falso, as mensagens não são marcadas como "vistas". Valor padrão: True |
withBody | Parâmetros | Pass True para devolver o corpo das mensagens especificadas. Se falso, apenas os cabeçalhos das mensagens são devolvidos. Valor padrão: 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. Se não forem encontrados objetos e-mail, uma coleção vazia é devolvida. |
notFound | Collection | Collection of:
|
Exemplo
Se quiser recuperar os 20 e-mails mais recentes sem alterar o seu estatuto de "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()
História
Release | Mudanças |
---|---|
18 R4 | Adicionado |
.getMIMEAsBlob( msgNumber : Integer { ; updateSeen : Boolean } ) : Blob
.getMIMEAsBlob( msgID : Text { ; updateSeen : Boolean } ) : Blob
Parâmetro | Tipo | Descrição | |
---|---|---|---|
msgNumber | Integer | -> | Número sequencial da mensagem |
msgID | Text | -> | ID única da mensagem |
updateSeen | Parâmetros | -> | Se Verdadeiro, a mensagem é marcada "visto" na caixa de correio. Se Falso, a mensagem é deixada intocada. |
Resultados | BLOB | <- | Blob da string MIME retornado do servidor mail |
Descrição
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
.
No primeiro parâmetro, pode passar qualquer um dos dois:
- 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()
.
Resultados
.getMIMEAsBlob()
returns a BLOB
which can be archived in a database or converted to an Email
object with the MAIL Convert from MIME
command.
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ória
Release | Mudanças |
---|---|
17 R5 | Adicionado |
.host : Text
Descrição
The .host
property contains the name or the IP address of the host server. Utilizado para transacções postais (SMTP, POP3, IMAP).
.logFile
História
Release | Mudanças |
---|---|
17 R5 | Adicionado |
.logFile : Text
Descrição
The .logFile
property contains the path of the extended log file defined (if any) for the mail connection. Pode ser relativo (à pasta atual de Logs) ou 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 mais informações sobre arquivos de registo estendidos, consultar:
- SMTP connections - 4DSMTPLog.txt
- POP3 connections - 4DPOP3Log.txt
- IMAP connections - 4DIMAPLog.txt
.move()
História
Release | Mudanças |
---|---|
18 R5 | Adicionado |
.move( msgsIDs : Collection ; destinationBox : Text ) : Object
.move( allMsgs : Integer ; destinationBox : Text ) : Object
Parâmetro | Tipo | Descrição | |
---|---|---|---|
msgsIDs | Collection | -> | Coleção de identificadores únicos de mensagens (strings) |
allMsgs | Integer | -> | IMAP all : All messages in the selected mailbox |
destinationBox | Text | -> | Caixa de correio para receber mensagens movimentadas |
Resultados | Object | <- | Estado da operação de mudança |
Descrição
The .move()
function 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.
Returned object
A função devolve um objecto que descreve o estado IMAP:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | Parâmetros | Verdadeiro se a operação for bem sucedida, Falso caso contrário | |
statusText | Text | Mensagem de estado devolvida pelo servidor IMAP, 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 IMAP) | |
[].errcode | Number | Código de erro 4D | |
[].message | Text | Descrição do erro 4D | |
[].componentSignature | Text | Assinatura da componente interna que devolveu o erro |
Exemplo 1
Para mover uma selecção de mensagens:
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
Para mover todas as mensagens na mailbox atual:
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ória
Release | Mudanças |
---|---|
18 R5 | Adicionado |
.numToID( startMsg : Integer ; endMsg : Integer ) : Collection
Parâmetro | Tipo | Descrição | |
---|---|---|---|
startMsg | Integer | -> | Número sequencial da primeira mensagem |
endMsg | Integer | -> | Número sequencial da última mensagem |
Resultados | Collection | <- | Colecção de identificações únicas |
Descrição
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.
Resultados
A função devolve uma colecção de cordas (identificações únicas).
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ória
Release | Mudanças |
---|---|
20 | Suporta palavras-chave personalizadas |
18 R6 | Adicionado |
.removeFlags( msgIDs : Collection ; keywords : Object ) : Object
.removeFlags( msgIDs : Text ; keywords : Object ) : Object
.removeFlags( msgIDs : Longint ; keywords : Object ) : Object
Parâmetro | Tipo | Descrição | |
---|---|---|---|
msgIDs | Collection | -> | Coleção de strings: IDs únicos de mensagens (texto) Texto: ID único de uma mensagem Longint (todos IMAP): Todas as mensagens na caixa de correio seleccionada |
keywords | Object | -> | Flags de palavras-chave a remover |
Resultados | Object | <- | Estado da operação removeFlags |
Descrição
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:
Parâmetros | Valor | Comentário |
---|---|---|
IMAP all | 1 | Seleccione todas as mensagens na caixa de correio seleccionada |
The keywords
parameter lets you define the flags to remove from msgIDs
. Pode passar qualquer uma das seguintes palavras-chave:
Parâmetro | Tipo | Descrição |
---|---|---|
$draft | Parâmetros | True para remover o flag "draft" na mensagem |
$seen | Parâmetros | True para remover a flag "seen" na mensagem |
$flagged | Parâmetros | True para remover a flag "flagged" na mensagem |
$answered | Parâmetros | True para remover a flag "answered" na mensagem |
$deleted | Parâmetros | True para remover a flag "deleted" na mensagem |
<custom flag> | Parâmetros | True para remover a flag personalizada na mensagem |
Please refer to .addFlags() for more information on custom flags.
- Para que uma palavra-chave seja tida em conta, tem de ser true.
Returned object
A função devolve um objecto que descreve o estado IMAP:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | Parâmetros | Verdadeiro se a operação for bem sucedida, Falso caso contrário | |
statusText | Text | Mensagem de estado devolvida pelo servidor IMAP, 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 IMAP) | |
[].errcode | Number | Código de erro 4D | |
[].message | Text | Descrição do erro 4D | |
[].componentSignature | Text | Assinatura da componente interna que devolveu o erro |
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"
// Criar transporter
$transporter:=IMAP New transporter($options)
// Selecionar mailbox
$boxInfo:=$transporter.selectBox("INBOX")
// Marcar todas as mensagens de INBOX como invisíveis
$flags:=New object
$flags["$seen"]:=True
$status:=$transporter.removeFlags(IMAP all;$flags)
.renameBox()
História
Release | Mudanças |
---|---|
19 | Adicionado |
.renameBox( currentName : Text ; newName : Text ) : Object
Parâmetro | Tipo | Descrição | |
---|---|---|---|
currentName | Text | -> | Nome da caixa de correio actual |
newName | Text | -> | Nome da nova caixa de correio |
Resultados | Object | <- | Estado da operação de renomeamento |
Descrição
The .renameBox()
function changes the name of a mailbox on the IMAP server. Tentar mudar o nome de uma caixa de correio de um nome de caixa de correio que não existe ou para um nome de caixa de correio que já existe irá gerar um erro.
In the currentName
parameter, pass the name of the mailbox to be renamed.
Pass the new name for the mailbox in the newName
parameter.
Returned object
A função devolve um objecto que descreve o estado IMAP:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | Parâmetros | Verdadeiro se a operação for bem sucedida, Falso caso contrário | |
statusText | Text | Mensagem de estado devolvida pelo servidor IMAP, 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 IMAP) | |
[].errcode | Number | Código de erro 4D | |
[].message | Text | Descrição do erro 4D | |
[].componentSignature | Text | Assinatura da componente interna que devolveu o erro |
Exemplo
Para renomear a sua caixa de correio "Invoices" para "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ória
Release | Mudanças |
---|---|
17 R4 | Adicionado |
.port : Integer
Descrição
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()
História
Release | Mudanças |
---|---|
18 R5 | Adicionado |
.searchMails( searchCriteria : Text ) : Collection
Parâmetro | Tipo | Descrição | |
---|---|---|---|
searchCriteria | Text | -> | Critérios de pesquisa |
Resultados | Collection | <- | Coleção de números de mensagens |
Descrição
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. Uma chave de pesquisa pode ser um único ou vários itens. Por exemplo:
SearchKey1 = FLAGGED SearchKey2 = NOT FLAGGED SearchKey3 = FLAGGED DRAFT
A correspondência não é normalmente sensível a maiúsculas e minúsculas
- 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
... devolve todas as mensagens com o conjunto de bandeiras visíveis OU o conjunto de bandeiras sinalizadoras
searchCriteria = NOT SEEN
... devolve todas as mensagens com a bandeira não estabelecida.
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 ”.
No que diz respeito aos dois últimos exemplos, note que o resultado da pesquisa é diferente quando se remove os parênteses da primeira lista de chaves de pesquisa.
- The searchCriteria may include the optional [CHARSET] specification. Esta consiste na palavra "CHARSET" seguida de uma palavra registada [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). Como padrão, os códigos 4D em Quotable Printable the searchCriteria string se conter caracteres estendidos
searchCriteria = CHARSET "ISO-8859" BODY "Help"
... significa que o critério de pesquisa utiliza o iso-8859 charset e o servidor terá de converter o critério de pesquisa antes de efectuar a pesquisa, se necessário.
Tipos de valores de pesquisa
As chaves de pesquisa podem solicitar o valor a pesquisar:
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. Se a string não conter quaisquer caracteres especiais, como o carácter espacial, por exemplo, não precisa de ser citada. A citação de tais strings assegurará que o seu valor de strings será interpretado 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. A correspondência não é sensível a maiúsculas e 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. Para números de sequência de mensagens, estes são números consecutivos de 1 até ao número total de mensagens na caixa de correio. Uma vírgula delimita números individuais; uma vírgula delimita entre dois 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.
Chaves de pesquisa autorizadas
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ória
Release | Mudanças |
---|---|
20 | id, flags, permanentFlags are returned |
18 R4 | Adicionado |
.selectBox( name : Text { ; state : Integer } ) : Object
Parâmetro | Tipo | Descrição | |
---|---|---|---|
name | Text | -> | Nome da nova caixa de correio |
state | Integer | -> | Estado de acesso à caixa de correio |
Resultados | Object | <- | objecto boxInfo |
Descrição
The .selectBox()
function 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. O nome representa uma hierarquia inequívoca da esquerda para a direita com níveis separados por um 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. Os valores possíveis são:
Parâmetros | Valor | Comentário |
---|---|---|
IMAP read only state | 1 | A caixa de correio seleccionada é acedida com privilégios apenas de leitura. As mensagens com uma flag "recente" (indicando novas mensagens) permanecem inalteradas. |
IMAP read write state | 0 | A caixa de correio seleccionada é acedida com privilégios de leitura e escrita. As mensagens são consideradas "vistas" e perdem o marcador "recente" (indicando novas mensagens). (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.
Returned object
The boxInfo
object returned contains the following properties:
Propriedade | Tipo | Descrição |
---|---|---|
name | Text | Nome da nova caixa de correio |
mailCount | number | Número de mensagens na caixa de email |
mailRecent | number | Número de mensagens com a flag "recent" |
id | text | Parâmetros |
flags | text | Lista de flags actualmente utilizadas para a caixa de correio, separadas por espaços |
permanentFlags | text | Lista de marcadores que o cliente pode mudar permanentemente (excepto a \Recent, que é gerida pelo servidor IMAP), separadas por espaços |
If permanentFlags
string includes the special flag *, it means that the server supports custom flags.
Exemplo
var $server; $boxinfo : Object
$server:=New object
$server.host:="imap.gmail.com" //Obrigatório
$server.user:="4d@gmail.com"
$server.password:="XXXXXXXX"
var $transporter : 4D.IMAPTransporter
$transporter:=IMAP New transporter($server)
$boxInfo:=$transporter.selectBox("INBOX")
.subscribe()
História
Release | Mudanças |
---|---|
19 | Adicionado |
.subscribe( name : Text ) : Object
Parâmetro | Tipo | Descrição | |
---|---|---|---|
name | Text | -> | Nome da nova caixa de correio |
Resultados | Object | <- | Estado da operação de subscrição |
Descrição
The .subscribe()
function allows adding or removing of the specified mailbox to/from the IMAP server’s set of “subscribed” mailboxes. Como tal, pode optar por restringir uma grande lista de caixas de correio disponíveis, subscrevendo as que normalmente deseja ver.
In the name
parameter, pass the name of the mailbox to add (subscribe) to your "subscribed" mailboxes.
Returned object
A função devolve um objecto que descreve o estado IMAP:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | Parâmetros | Verdadeiro se a operação for bem sucedida, Falso caso contrário | |
statusText | Text | Mensagem de estado devolvida pelo servidor IMAP, 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 IMAP) | |
[].errcode | Number | Código de erro 4D | |
[].message | Text | Descrição do erro 4D | |
[].componentSignature | Text | Assinatura da componente interna que devolveu o erro |
Exemplo
Para subscrever a caixa de correio "Atlas Corp" na hierarquia "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()
História
Release | Mudanças |
---|---|
19 | Adicionado |
.unsubscribe( name : Text ) : Object
Parâmetro | Tipo | Descrição | |
---|---|---|---|
name | Text | -> | Nome da nova caixa de correio |
Resultados | Object | <- | Estado da operação unsubscribe |
Descrição
The .unsubscribe()
function removes a mailbox from a set of subscribed mailboxes. Isto permite reduzir o número de caixas de correio que normalmente se vêem.
In the name
parameter, pass the name of the mailbox to remove (unsubscribe) from your active mailboxes.
Returned object
A função devolve um objecto que descreve o estado IMAP:
Propriedade | Tipo | Descrição | |
---|---|---|---|
success | Parâmetros | Verdadeiro se a operação for bem sucedida, Falso caso contrário | |
statusText | Text | Mensagem de estado devolvida pelo servidor IMAP, 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 IMAP) | |
[].errcode | Number | Código de erro 4D | |
[].message | Text | Descrição do erro 4D | |
[].componentSignature | Text | Assinatura da componente interna que devolveu o erro |
Exemplo
Para cancelar a subscrição da caixa de correio "Atlas Corp" na hierarquia "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
História
Release | Mudanças |
---|---|
17 R4 | Adicionado |
.user : Text
Descrição
The .user
property contains the user name used for authentication on the mail server.