Saltar para o conteúdo principal
Versão: 20 R5 BETA

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
ReleaseMudanças
18 R4Adicionado

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

ParâmetroTipoDescrição
serverObject->Informação de servidor de correio
Resultados4D.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:

serverValor padrão (se omitido)
.acceptUnsecureConnection : Boolean&nbsp;&nbsp;&nbsp;&nbsp;True if 4D is allowed to establish an unencrypted connectionFalse
.accessTokenOAuth2: Text
.accessTokenOAuth2: Object
Text string or token object representing OAuth2 authorization credentials. Used only with OAUTH2 authenticationMode. If accessTokenOAuth2 is used but authenticationMode is omitted, the OAuth 2 protocol is used (if allowed by the server). Not returned in IMAP transporter object.
nenhum
.authenticationMode : Text&nbsp;&nbsp;&nbsp;&nbsp;the authentication mode used to open the session on the mail servero modo de autenticação mais seguro disponível no servidor é usado
.checkConnectionDelay : Integer&nbsp;&nbsp;&nbsp;&nbsp;the maximum time (in seconds) allowed prior to checking the connection to the server300
.connectionTimeOut : Integer&nbsp;&nbsp;&nbsp;&nbsp;the maximum wait time (in seconds) allowed to establish a connection to the server30
.host : Text&nbsp;&nbsp;&nbsp;&nbsp;the name or the IP address of the host servermandatory
.logFile : Text&nbsp;&nbsp;&nbsp;&nbsp;the path of the extended log file defined (if any) for the mail connectionnenhum
.password : Text
User password for authentication on the server. Not returned in IMAP transporter object.
nenhum
.port : Integer&nbsp;&nbsp;&nbsp;&nbsp; the port number used for mail transactions993
.user : Text&nbsp;&nbsp;&nbsp;&nbsp; the user name used for authentication on the mail servernenhum

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âmetroTipoDescrição
serverObject->Informação de servidor de correio
Resultados4D.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
ReleaseMudanças
17 R4Adicionado

.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
ReleaseMudanças
20Suporta palavras-chave personalizadas
18 R6Adicionado

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

ParâmetroTipoDescrição
msgIDsCollection->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
keywordsObject->Flags de palavras chaves a adicionar
ResultadosObject<-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âmetrosValorComentário
IMAP all1Seleccione 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:

PropriedadeTipoDescrição
$draftParâmetrosTrue para adicionar o marcador "draft" na mensagem
$seenParâmetrosTrue para adicionar o marcador "seen" na mensagem
$flaggedParâmetrosTrue para adicionar o marcador "flagged" na mensagem
$answeredParâmetrosTrue para adicionar o marcador "answered" na mensagem
$deletedParâmetrosTrue para adicionar o marcador "deleted" na mensagem
<custom flag>ParâmetrosTrue 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:

PropriedadeTipoDescrição
successParâmetrosVerdadeiro se a operação for bem sucedida, Falso caso contrário
statusTextTextMensagem de estado devolvida pelo servidor IMAP, ou último erro devolvido na pilha de erros 4D
errorsCollectionpilha de erros 4D (não devolvida se for recebida uma resposta do servidor IMAP)
[].errcodeNumberCódigo de erro 4D
[].messageTextDescrição do erro 4D
[].componentSignatureTextAssinatura 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
ReleaseMudanças
18 R6Adicionado

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

ParâmetroTipoDescrição
mailObjObject->Objeto Email
destinationBoxText->Caixa de email que vai receber o objeto Email
optionsObject->Objeto que contém informações do charset
ResultadosObject<-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:

PropriedadeTipoDescrição
headerCharsetTextCharset 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
bodyCharsetTextCharset 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âmetrosValorComentário
mail mode ISO2022JPUS-ASCII_ISO-2022-JP_UTF8_QP
  • headerCharset: US-ASCII if possible, Japanese (ISO-2022-JP) & Quoted-printable if possible, otherwise UTF-8 & Quoted-printable
  • bodyCharset: US-ASCII if possible, Japanese (ISO-2022-JP) & 7-bit if possible, otherwise UTF-8 & Quoted-printable
mail mode ISO88591ISO-8859-1
  • headerCharset: ISO-8859-1 & Quoted-printable
  • bodyCharset: ISO-8859-1 & 8-bit
mail mode UTF8US-ASCII_UTF8_QPheaderCharset & bodyCharset: US-ASCII se possível, caso contrário UTF-8 & Quoted-printable (valor padrão)
modo de correio UTF8 na base64US-ASCII_UTF8_B64headerCharset & 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:

PropriedadeTipoDescrição
successParâmetrosVerdadeiro se a operação for bem sucedida, Falso caso contrário
statusTextTextMensagem de estado devolvida pelo servidor IMAP, ou último erro devolvido na pilha de erros 4D
errorsCollectionpilha de erros 4D (não devolvida se for recebida uma resposta do servidor IMAP)
[].errcodeNumberCódigo de erro 4D
[].messageTextDescrição do erro 4D
[].componentSignatureTextAssinatura 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
ReleaseMudanças
17 R4Adicionado

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

ValorConstantesComentário
CRAM-MD5IMAP authentication CRAM MD5Autenticação usando o protocolo CRAM-MD5
LOGINIMAP authentication loginAutenticação usando o protocolo LOGIN
OAUTH2Autenticação IMAP OAUTH2Autenticação usando o protocolo OAuth2
PLAINIMAP authentication plainAutenticação usando o protocolo PLAIN

.checkConnection()

História
ReleaseMudanças
17 R4Adicionado

.checkConnection() : Object

ParâmetroTipoDescrição
ResultadosObject<-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:

PropriedadeTipoDescrição
successbooleanVerdadeiro se a verificação for bem sucedida, Falso de outra forma
statusnumber(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)
statusTexttextMensagem de estado devolvida pelo servidor de correio, ou último erro devolvido na pilha de erros 4D
errorscollectionpilha de erros 4D (não devolvida se for recebida uma resposta do servidor de correio)
[ ].errCodenumberCódigo de erro 4D
[ ].messagetextDescrição do erro 4D
[ ].componentSignaturetextAssinatura da componente interna que devolveu o erro

.checkConnectionDelay

História
ReleaseMudanças
18 R4Adicionado

.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
ReleaseMudanças
17 R5Adicionado

.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
ReleaseMudanças
18 R5Adicionado

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

ParâmetroTipoDescrição
msgsIDsCollection->Coleção de identificadores únicos de mensagens (strings)
allMsgsInteger->IMAP all: All messages in the selected mailbox
destinationBoxText->Caixa de correio para receber mensagens copiadas
ResultadosObject<-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:

PropriedadeTipoDescrição
successParâmetrosVerdadeiro se a operação for bem sucedida, Falso caso contrário
statusTextTextMensagem de estado devolvida pelo servidor IMAP, ou último erro devolvido na pilha de erros 4D
errorsCollectionpilha de erros 4D (não devolvida se for recebida uma resposta do servidor IMAP)
[].errcodeNumberCódigo de erro 4D
[].messageTextDescrição do erro 4D
[].componentSignatureTextAssinatura 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
ReleaseMudanças
19Adicionado

.createBox( name : Text ) : Object

ParâmetroTipoDescrição
nameText->Nome da nova caixa de correio
ResultadosObject<-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:

PropriedadeTipoDescrição
successParâmetrosVerdadeiro se a operação for bem sucedida, Falso caso contrário
statusTextTextMensagem de estado devolvida pelo servidor IMAP, ou último erro devolvido na pilha de erros 4D
errorsCollectionpilha de erros 4D (não devolvida se for recebida uma resposta do servidor IMAP)
[].errcodeNumberCódigo de erro 4D
[].messageTextDescrição do erro 4D
[].componentSignatureTextAssinatura 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
ReleaseMudanças
18 R5Adicionado

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

ParâmetroTipoDescrição
msgsIDsCollection->Coleção de identificadores únicos de mensagens (strings)
allMsgsInteger->IMAP all: All messages in the selected mailbox
ResultadosObject<-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, the IMAP 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:

PropriedadeTipoDescrição
successParâmetrosVerdadeiro se a operação for bem sucedida, Falso caso contrário
statusTextTextMensagem de estado devolvida pelo servidor IMAP, ou último erro devolvido na pilha de erros 4D
errorsCollectionpilha de erros 4D (não devolvida se for recebida uma resposta do servidor IMAP)
[].errcodeNumberCódigo de erro 4D
[].messageTextDescrição do erro 4D
[].componentSignatureTextAssinatura 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
ReleaseMudanças
19Adicionado

.deleteBox( name : Text ) : Object

ParâmetroTipoDescrição
nameText->Nome da caixa de correio a apagar
ResultadosObject<-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:

PropriedadeTipoDescrição
successParâmetrosVerdadeiro se a operação for bem sucedida, Falso caso contrário
statusTextTextMensagem de estado devolvida pelo servidor IMAP, ou último erro devolvido na pilha de erros 4D
errorsCollectionpilha de erros 4D (não devolvida se for recebida uma resposta do servidor IMAP)
[].errcodeNumberCódigo de erro 4D
[].messageTextDescrição do erro 4D
[].componentSignatureTextAssinatura 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
ReleaseMudanças
18 R6Adicionado

.expunge() : Object

ParâmetroTipoDescrição
ResultadosObject<-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:

PropriedadeTipoDescrição
successParâmetrosVerdadeiro se a operação for bem sucedida, Falso caso contrário
statusTextTextMensagem de estado devolvida pelo servidor IMAP, ou último erro devolvido na pilha de erros 4D
errorsCollectionpilha de erros 4D (não devolvida se for recebida uma resposta do servidor IMAP)
[].errcodeNumberCódigo de erro 4D
[].messageTextDescrição do erro 4D
[].componentSignatureTextAssinatura 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
ReleaseMudanças
20id is returned
18 R5name is optional
18 R4Adicionado

.getBoxInfo( { name : Text }) : Object

ParâmetroTipoDescrição
nameText->Nome da nova caixa de correio
ResultadosObject<-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:

PropriedadeTipoDescrição
nametextNome da nova caixa de correio
mailCountnumberNúmero de mensagens na caixa de email
mailRecentnumberNúmero de mensagens com o marcador "recente" (indicando novas mensagens)
idtextParâ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
ReleaseMudanças
18 R4Adicionado
19Add isSubscribed parameter

.getBoxList( { parameters : Object } ) : Collection

ParâmetroTipoDescrição
parametersObject->Parâmetros
ResultadosCollection<-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:

PropriedadeTipoDescrição
isSubscribedParâmetros
  • True to return only subscribed mailboxes
  • False to return all available mailboxes
  • Resultados

    Cada objecto da coleção devolvida contém as seguintes propriedades:

    PropriedadeTipoDescrição
    [].nametextNome da nova caixa de correio
    [].selectablebooleanIndicates whether or not the access rights allow the mailbox to be selected:
    • true - the mailbox can be selected
    • false - the mailbox can not be selected
    [].inferiorbooleanIndicates whether or not the access rights allow creating a lower hierachy in the mailbox:
    • true - a lower level can be created
    • false - a lower level can not be created
    [].interestingbooleanIndicates if the mailbox has been marked "interesting" by the server:
    • true - The mailbox has been marked "interesting" by the server. For example, it may contain new messages.
    • false - The mailbox has not been marked "interesting" by the server.

    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
    ReleaseMudanças
    18 R4Adicionado

    .getDelimiter() : Text

    ParâmetroTipoDescrição
    ResultadosText<-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.

    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
    ReleaseMudanças
    18 R4Adicionado

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

    ParâmetroTipoDescrição
    msgNumberInteger->Número sequencial da mensagem
    msgIDText->ID única da mensagem
    optionsObject->Instruções de tratamento de mensagens
    ResultadosObject<-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:

    PropriedadeTipoDescrição
    updateSeenbooleanSe Verdadeiro, a mensagem é marcada como "visto" na caixa de correio. Se falso, a mensagem não é marcada como "visto". Valor padrão: True
    withBodybooleanPass 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
    ReleaseMudanças
    18 R5Adicionado

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

    ParâmetroTipoDescrição
    idsCollection->Colecção de identificação da mensagem
    startMsgInteger->Número sequencial da primeira mensagem
    endMsgInteger->Número sequencial da última mensagem
    optionsObject->Instruções de tratamento de mensagens
    ResultadosObject<-Object containing:
    • a collection of Email objects and
    • a collection of IDs or numbers for missing messages, if any

    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

    PropriedadeTipoDescrição
    updateSeenParâmetrosSe 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
    withBodyParâmetrosPass 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:

    PropriedadeTipoDescrição
    listaCollectionCollection of Email objects. Se não forem encontrados objetos e-mail, uma coleção vazia é devolvida.
    notFoundCollectionCollection of:
    • first syntax - previously passed message IDs that do not exist
    • second syntax - sequence numbers of messages between startMsg and endMsg that do not exist
    An empty collection is returned if all messages are found.

    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
    ReleaseMudanças
    18 R4Adicionado

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

    ParâmetroTipoDescrição
    msgNumberInteger->Número sequencial da mensagem
    msgIDText->ID única da mensagem
    updateSeenParâmetros->Se Verdadeiro, a mensagem é marcada "visto" na caixa de correio. Se Falso, a mensagem é deixada intocada.
    ResultadosBLOB<-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
    ReleaseMudanças
    17 R5Adicionado

    .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
    ReleaseMudanças
    17 R5Adicionado

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

    .move()

    História
    ReleaseMudanças
    18 R5Adicionado

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

    ParâmetroTipoDescrição
    msgsIDsCollection->Coleção de identificadores únicos de mensagens (strings)
    allMsgsInteger->IMAP all: All messages in the selected mailbox
    destinationBoxText->Caixa de correio para receber mensagens movimentadas
    ResultadosObject<-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:

    PropriedadeTipoDescrição
    successParâmetrosVerdadeiro se a operação for bem sucedida, Falso caso contrário
    statusTextTextMensagem de estado devolvida pelo servidor IMAP, ou último erro devolvido na pilha de erros 4D
    errorsCollectionpilha de erros 4D (não devolvida se for recebida uma resposta do servidor IMAP)
    [].errcodeNumberCódigo de erro 4D
    [].messageTextDescrição do erro 4D
    [].componentSignatureTextAssinatura 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
    ReleaseMudanças
    18 R5Adicionado

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

    ParâmetroTipoDescrição
    startMsgInteger->Número sequencial da primeira mensagem
    endMsgInteger->Número sequencial da última mensagem
    ResultadosCollection<-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
    ReleaseMudanças
    20Suporta palavras-chave personalizadas
    18 R6Adicionado

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

    ParâmetroTipoDescrição
    msgIDsCollection->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
    keywordsObject->Flags de palavras-chave a remover
    ResultadosObject<-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âmetrosValorComentário
    IMAP all1Seleccione 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âmetroTipoDescrição
    $draftParâmetrosTrue para remover o flag "draft" na mensagem
    $seenParâmetrosTrue para remover a flag "seen" na mensagem
    $flaggedParâmetrosTrue para remover a flag "flagged" na mensagem
    $answeredParâmetrosTrue para remover a flag "answered" na mensagem
    $deletedParâmetrosTrue para remover a flag "deleted" na mensagem
    <custom flag>ParâmetrosTrue 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:

    PropriedadeTipoDescrição
    successParâmetrosVerdadeiro se a operação for bem sucedida, Falso caso contrário
    statusTextTextMensagem de estado devolvida pelo servidor IMAP, ou último erro devolvido na pilha de erros 4D
    errorsCollectionpilha de erros 4D (não devolvida se for recebida uma resposta do servidor IMAP)
    [].errcodeNumberCódigo de erro 4D
    [].messageTextDescrição do erro 4D
    [].componentSignatureTextAssinatura 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
    ReleaseMudanças
    19Adicionado

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

    ParâmetroTipoDescrição
    currentNameText->Nome da caixa de correio actual
    newNameText->Nome da nova caixa de correio
    ResultadosObject<-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:

    PropriedadeTipoDescrição
    successParâmetrosVerdadeiro se a operação for bem sucedida, Falso caso contrário
    statusTextTextMensagem de estado devolvida pelo servidor IMAP, ou último erro devolvido na pilha de erros 4D
    errorsCollectionpilha de erros 4D (não devolvida se for recebida uma resposta do servidor IMAP)
    [].errcodeNumberCódigo de erro 4D
    [].messageTextDescrição do erro 4D
    [].componentSignatureTextAssinatura 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
    ReleaseMudanças
    17 R4Adicionado

    .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
    ReleaseMudanças
    18 R5Adicionado

    .searchMails( searchCriteria : Text ) : Collection

    ParâmetroTipoDescrição
    searchCriteriaText->Critérios de pesquisa
    ResultadosCollection<-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 or Convert 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:* is 2,4,5,6,7,9,12,13,14,15 for a mailbox with 15 messages. searchCriteria = 1:5 ANSWERED search in message selection from message sequence number 1 to 5 for messages which have the \Answered flag set. searchCriteria= 2,4 ANSWERED search in the message selection (message numbers 2 and 4) for messages which have the \Answered flag set.

    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
    ReleaseMudanças
    20id, flags, permanentFlags are returned
    18 R4Adicionado

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

    ParâmetroTipoDescrição
    nameText->Nome da nova caixa de correio
    stateInteger->Estado de acesso à caixa de correio
    ResultadosObject<-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âmetrosValorComentário
    IMAP read only state1A 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 state0A 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:

    PropriedadeTipoDescrição
    nameTextNome da nova caixa de correio
    mailCountnumberNúmero de mensagens na caixa de email
    mailRecentnumberNúmero de mensagens com a flag "recent"
    idtextParâmetros
    flagstextLista de flags actualmente utilizadas para a caixa de correio, separadas por espaços
    permanentFlagstextLista de marcadores que o cliente pode mudar permanentemente (excepto a \Recent, que é gerida pelo servidor IMAP), separadas por espaços
    info

    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
    ReleaseMudanças
    19Adicionado

    .subscribe( name : Text ) : Object

    ParâmetroTipoDescrição
    nameText->Nome da nova caixa de correio
    ResultadosObject<-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:

    PropriedadeTipoDescrição
    successParâmetrosVerdadeiro se a operação for bem sucedida, Falso caso contrário
    statusTextTextMensagem de estado devolvida pelo servidor IMAP, ou último erro devolvido na pilha de erros 4D
    errorsCollectionpilha de erros 4D (não devolvida se for recebida uma resposta do servidor IMAP)
    [].errcodeNumberCódigo de erro 4D
    [].messageTextDescrição do erro 4D
    [].componentSignatureTextAssinatura 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
    ReleaseMudanças
    19Adicionado

    .unsubscribe( name : Text ) : Object

    ParâmetroTipoDescrição
    nameText->Nome da nova caixa de correio
    ResultadosObject<-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:

    PropriedadeTipoDescrição
    successParâmetrosVerdadeiro se a operação for bem sucedida, Falso caso contrário
    statusTextTextMensagem de estado devolvida pelo servidor IMAP, ou último erro devolvido na pilha de erros 4D
    errorsCollectionpilha de erros 4D (não devolvida se for recebida uma resposta do servidor IMAP)
    [].errcodeNumberCódigo de erro 4D
    [].messageTextDescrição do erro 4D
    [].componentSignatureTextAssinatura 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
    ReleaseMudanças
    17 R4Adicionado

    .user : Text

    Descrição

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