Skip to main content
Version: v19 R8 BETA

IMAPTransporter

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

IMAP Transporter object

IMAP Transporter objects are instantiated with the IMAP New transporter command. Eles oferecem as propriedades abaixo e funções:

.acceptUnsecureConnection : Boolean    Verdadeiro se 4D for permitido estabelecer uma ligação não encriptada
.addFlags( msgIDs : Collection ; keywords : Object ) : Object
.addFlags( msgIDs : Text ; keywords : Object ) : Object
.addFlags( msgIDs : Longint ; keywords : Object ) : Object
    adds flags to the msgIDs for the specified keywords
.append( mailObj : Object ; destinationBox : Text ; options : Object ) : Object    appends a mailObj to the destinationBox
.authenticationMode : Text    o modo de autenticação utilizado para abrir a sessão no servidor de correio
.checkConnection() : Object     verifica a ligação utilizando a informação armazenada no objeto de transporte
.checkConnectionDelay : Integer    the maximum time (in seconds) allowed prior to checking the connection to the server
.connectionTimeOut : Integer    o tempo máximo de espera (em segundos) permitido para estabelecer uma conexão com o servidor
.copy( msgsIDs : Collection ; destinationBox : Text ) : Object
.copy( allMsgs : Integer ; destinationBox : Text ) : Object
    copies the messages defined by msgsIDs or allMsgs to the destinationBox on the IMAP server
.createBox( name : Text ) : Object    creates a mailbox with the given name
.delete( msgsIDs : Collection ) : Object
.delete( allMsgs : Integer ) : Object
    sets the "deleted" flag for the messages defined in msgsIDs or allMsgs
.deleteBox( name : Text ) : Object    permanently removes the mailbox with the given name from the IMAP server
.expunge() : Object    removes all messages with the "deleted" flag from the IMAP mail server.
.getBoxInfo( { name : Text }) : Object    returns a boxInfo object corresponding to the current maibox, or the mailbox name
.getBoxList( { parameters : Object } ) : Collection    returns a collection of mailboxes describing all of the available mailboxes
.getDelimiter() : Text    returns the character used to delimit levels of hierarchy in the mailbox name
.getMail( msgNumber: Integer { ; options : Object } ) : Object
.getMail( msgID: Text { ; options : Object } ) : Object
    returns the Email object corresponding to the msgNumber or msgID in the mailbox designated by the IMAP_transporter
.getMails( ids : Collection { ; options : Object } ) : Object
.getMails( startMsg : Integer ; endMsg : Integer { ; options : Object } ) : Object
    returns an object containing a collection of Email objects
.getMIMEAsBlob( msgNumber : Integer { ; updateSeen : Boolean } ) : Blob
.getMIMEAsBlob( msgID : Text { ; updateSeen : Boolean } ) : Blob
    returns a BLOB containing the MIME contents for the message corresponding to the msgNumber or msgID in the mailbox designated by the IMAP_transporter
.host : Text    o nome ou o endereço IP do servidor anfitrião
.logFile : Text    o caminho do arquivo de registo alargado definido (se existir) para a ligação de correio
.move( msgsIDs : Collection ; destinationBox : Text ) : Object
.move( allMsgs : Integer ; destinationBox : Text ) : Object
    moves the messages defined by msgsIDs or allMsgs to the destinationBox on the IMAP server
.numToID( startMsg : Integer ; endMsg : Integer ) : Collection    converts the sequence numbers to IMAP unique IDs for the messages in the sequential range designated by startMsg and endMsg
.removeFlags( msgIDs : Collection ; keywords : Object ) : Object
.removeFlags( msgIDs : Text ; keywords : Object ) : Object
.removeFlags( msgIDs : Longint ; keywords : Object ) : Object
    removes flags from the msgIDs for the specified keywords
.renameBox( currentName : Text ; newName : Text ) : Object    changes the name of a mailbox on the IMAP server
.port : Integer     o número do porto utilizado para as transações postais
.searchMails( searchCriteria : Text ) : Collection    searches for messages that match the given searchCriteria in the current mailbox
.selectBox( name : Text { ; state : Integer } ) : Object    selects the name mailbox as the current mailbox
.subscribe( name : Text ) : Object    allows adding or removing of the specified mailbox to/from the IMAP server’s set of “subscribed” mailboxes
.unsubscribe( name : Text ) : Object    removes a mailbox from a set of subscribed mailboxes
.user : Text     o nome de usuário utilizado para autenticação no servidor de correio

IMAP New transporter

Histórico
VersãoMudanças
v18 R4Adicionado

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

ParâmetrosTipoDescrição
serverObjeto->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.

No parâmetro server, passe um objeto contendo as propriedades abaixo:

serverValor padrão (se omitido)
.acceptUnsecureConnection : Boolean    Verdadeiro se 4D for permitido estabelecer uma ligação não encriptadaFalse
.accessTokenOAuth2: Text
.accessTokenOAuth2: Object
Text string or token object representing OAuth2 authorization credentials. Só é usado com OAUTH2 authenticationMode. Se accessTokenOAuth2 for usado mas authenticationMode for omitido, o protocolo OAuth 2 é usado (se permitido pelo servidor). Not returned in IMAP transporter object.
nenhum
.authenticationMode : Text    o modo de autenticação utilizado para abrir a sessão no servidor de correioo 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 server300
.connectionTimeOut : Integer    o tempo máximo de espera (em segundos) permitido para estabelecer uma conexão com o servidor30
.host : Text    o nome ou o endereço IP do servidor anfitriãoobrigatório
.logFile : Text    o caminho do arquivo de registo alargado definido (se existir) para a ligação de correionenhum
.password : Text
User password for authentication on the server. Not returned in IMAP transporter object.
nenhum
.port : Integer     o número do porto utilizado para as transações postais993
.user : Text     o nome de usuário utilizado para autenticação no servidor de correionenhum

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

Resultados

The function returns an IMAP transporter object. Todas as propriedades retornadas sãoapenas leitura.

The IMAP connection is automatically closed when the transporter object is destroyed.

Exemplo

$server:=New object
$server.host:="imap.gmail.com" //Obrigatório
$server.port:=993
$server.user:="4d@gmail.com"
$server.password:="XXXXXXXX"
$server.logFile:="LogTest.txt" //log para salvar na pasta Logs

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

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

4D.IMAPTransporter.new()

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

ParâmetrosTipoDescrição
serverObjeto->Informação de servidor de correio
Resultados4D.IMAPTransporter<-IMAP transporter object

|

Descrição

A função 4D.IMAPTransporter.new() creates and returns a new object of the 4D.IMAPTransporter type. It is identical to the IMAP New transporter command (shortcut).

.acceptUnsecureConnection

Histórico
VersãoMudanças
v17 R4Adicionado

.acceptUnsecureConnection : Boolean

Descrição

A propriedade .acceptUnsecureConnection contém Verdadeiro se 4D for permitido estabelecer uma ligação não encriptada quando a ligação encriptada não é possível.

Contém False se conexões cifradas não forem permitidas, neste caso um erro é retornado quando a conexão criptografada não for possível.

Estão disponíveis portos seguros:

  • SMTP

    • 465: SMTPS
    • 587 ou 25: SMTP com atualização STARTTLS se for compat[ivel com o servidor.
  • IMAP

    • 143: IMAP non-encrypted port
    • 993: IMAP com atualização STARTTLS se for compatível com o servidor
  • POP3

    • 110: Porta não criptografada POP3
    • 995: POP3 com atualização STARTTLS se suportado pelo servidor.

.addFlags()

Histórico
VersãoMudanças
v18 R6Adicionado

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

ParâmetrosTipoDescrição
msgIDsCollection->Collection of strings: Message unique IDs (text)
Text: Unique ID of a message
Longint (IMAP all): All messages in the selected mailbox
keywordsObjeto->Keyword flags to add
ResultadosObjeto<-Status of the addFlags operation

|

Descrição

A função .addFlags() adds flags to the msgIDs for the specified keywords.

In the msgIDs parameter, you can pass either:

  • a collection containing the unique IDs of specific messages or

  • the unique ID (text) of a single message or

  • the following constant (longint) for all messages in the selected mailbox:

    ConstanteValueComentário
    IMAP all1Select all messages in the selected mailbox

The keywords parameter lets you pass an object with keyword values for specific flags to add to msgIDs. You can pass any of the following keywords:

ParâmetrosTipoDescrição
$draftBooleanoTrue to add the "draft" flag to the message
$seenBooleanoTrue to add the "seen" flag to the message
$flaggedBooleanoTrue to add the "flagged" flag to the message
$answeredBooleanoTrue to add the "answered" flag to the message
$deletedBooleanoTrue to add the "deleted" flag to the message
  • False values are ignored.
  • The interpretation of keyword flags may vary per mail client.

Objeto devolvido

The function returns an object describing the IMAP status:

PropriedadeTipoDescrição
successBooleanoTrue if the operation is successful, False otherwise
statusTextTextStatus message returned by the IMAP server, or last error returned in the 4D error stack
errorsCollection4D error stack (not returned if a IMAP server response is received)
[].errcodeNúmero4D error code
[].messageTextDescription of the 4D error
[].componentSignatureTextSignature of the internal component which returned the error

Exemplo

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

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

// Create transporter
$transporter:=IMAP New transporter($options)

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

// Mark all messages from INBOX as read/seen
$flags:=New object
$flags["$seen"]:=True
$status:=$transporter.addFlags(IMAP all;$flags)

.append()

Histórico
VersãoMudanças
v18 R6Adicionado

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

ParâmetrosTipoDescrição
mailObjObjeto->Objeto Email
destinationBoxText->Mailbox to receive Email object
optionsObjeto->Object containing charset info
ResultadosObjeto<-Status of the append operation

|

Descrição

A função .append() appends a mailObj to the destinationBox.

In the mailObj parameter, pass an Email object. In the mailObj parameter, pass an Email object. The .append() function supports keyword tags in the Email object's keywords attribute.

The optional destinationBox parameter lets you pass the name of a mailbox where the mailObj will be appended. If omitted, the current mailbox is used.

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

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. Possible values: See possible charsets table below
bodyCharsetTextCharset e codificação usados para o conteúdo html e corpo do e-mail. Possible values: See possible charsets table below

Possible charsets:

ConstanteValueComentário
mail mode ISO2022JPUS-ASCII_ISO-2022-JP_UTF8_QP
  • headerCharset: US-ASCII se possível, japonês (ISO-2022-JP) & impressora, se possível, caso contrário, 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 if possible, otherwise UTF-8 & Quoted-printable (default value)
modo de correio UTF8 na base64US-ASCII_UTF8_B64headerCharset & bodyCharset: US-ASCII if possible, otherwise UTF-8 & base64

Objeto devolvido

The function returns an object describing the IMAP status:

PropriedadeTipoDescrição
successBooleanoTrue if the operation is successful, False otherwise
statusTextTextStatus message returned by the IMAP server, or last error returned in the 4D error stack
errorsCollection4D error stack (not returned if a IMAP server response is received)
[].errcodeNúmero4D error code
[].messageTextDescription of the 4D error
[].componentSignatureTextSignature of the internal component which returned the error

Exemplo

To save an email in the Drafts mailbox:

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

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

$imap:=IMAP New transporter($settings)

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

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

.authenticationMode

Histórico
VersãoMudanças
v17 R4Adicionado

.authenticationMode : Text

Descrição

A propriedade .authenticationMode< contém o modo de autenticação utilizado para abrir a sessão no servidor de correio.

Por padrão, o modo mais seguro suportado pelo servidor é usado.

Valores possíveis:

ValueConstantesComentário
CRAM-MD5IMAP authentication CRAM MD5Autenticação usando o protocolo CRAM-MD5
LOGINAutenticação do login/acessoAutenticação usando o protocolo LOGIN
OAUTH2Autenticação IMAP OAUTH2Autenticação usando o protocolo OAuth2
PLAINIMAP authentication plainAutenticação usando o protocolo PLAIN

.checkConnection()

Histórico
VersãoMudanças
v17 R4Adicionado

.checkConnection() : Object

ParâmetrosTipoDescrição
ResultadosObjeto<-Estado da ligação do objecto transportador

|

Descrição

A função .checkConnection() verifica a ligação utilizando a informação armazenada no objeto de transporte, recria a ligação, se necessário, e devolve o estado. Esta função permite verificar se os valores fornecidos pelo utilizador são válidos e consistentes.

Objeto devolvido

A função envia um pedido para o servidor de correio e devolve um objecto descrevendo o estado do correio. This object can contain the following properties:

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)
[ ].errCodenumber4D error code
[ ].messagetextDescription of the 4D error
[ ].componentSignaturetextSignature of the internal component which returned the error

.checkConnectionDelay

Histórico
VersãoMudanças
v18 R4Adicionado

.checkConnectionDelay : Integer

Descrição

The .checkConnectionDelay property contains the maximum time (in seconds) allowed prior to checking the connection to the server. If this time is exceeded between two method calls, the connection to the server will be checked. By default, if the property has not been set in the server object, the value is 300.

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

.connectionTimeOut

Histórico
VersãoMudanças
v17 R5Adicionado

.connectionTimeOut : Integer

Descrição

A propriedade .connectionTimeOut contém o tempo máximo de espera (em segundos) permitido para estabelecer uma conexão com o servidor. Por padrão, se a propriedade não tiver sido definida no objecto servidor (utilizado para criar o objecto transportador com SMTP Novo transportador, POP3 Novo transportador, ou IMAP Novo transportador), o valor é 30.

.copy()

Histórico
VersãoMudanças
v18 R5Adicionado

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

ParâmetrosTipoDescrição
msgsIDsCollection->Collection of message unique IDs (strings)
allMsgsInteger->IMAP all: All messages in the selected mailbox
destinationBoxText->Mailbox to receive copied messages
ResultadosObjeto<-Status of the copy operation

|

Descrição

A função .copy() copies the messages defined by msgsIDs or allMsgs to the destinationBox on the IMAP server.

Pode passar:

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

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

Objeto devolvido

The function returns an object describing the IMAP status:

PropriedadeTipoDescrição
successBooleanoTrue if the operation is successful, False otherwise
statusTextTextStatus message returned by the IMAP server, or last error returned in the 4D error stack
errorsCollection4D error stack (not returned if a IMAP server response is received)
[].errcodeNúmero4D error code
[].messageTextDescription of the 4D error
[].componentSignatureTextSignature of the internal component which returned the error

Exemplo 1

To copy a selection of messages:

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

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

$transporter:=IMAP New transporter($server)

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

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

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

Exemplo 2

To copy all messages in the current mailbox:

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

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

$transporter:=IMAP New transporter($server)

//select mailbox

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

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

.createBox()

Histórico
VersãoMudanças
v19Adicionado

.createBox( name : Text ) : Object

ParâmetrosTipoDescrição
nameText->Name of the new mailbox
ResultadosObjeto<-Status of the mailbox creation operation

|

Descrição

A função .createBox() creates a mailbox with the given name. If the IMAP server’s hierarchy separator character appears elsewhere in the mailbox name, the IMAP server will create any parent names needed to create the given mailbox.

In other words, an attempt to create "Projects/IMAP/Doc" on a server in which "/" is the hierarchy separator character will create:

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

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

Objeto devolvido

The function returns an object describing the IMAP status:

PropriedadeTipoDescrição
successBooleanoTrue if the operation is successful, False otherwise
statusTextTextStatus message returned by the IMAP server, or last error returned in the 4D error stack
errorsCollection4D error stack (not returned if a IMAP server response is received)
[].errcodeNúmero4D error code
[].messageTextDescription of the 4D error
[].componentSignatureTextSignature of the internal component which returned the error

Exemplo

To create a new “Invoices” mailbox:

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

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

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

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

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

.delete()

Histórico
VersãoMudanças
v18 R5Adicionado

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

ParâmetrosTipoDescrição
msgsIDsCollection->Collection of message unique IDs (strings)
allMsgsInteger->IMAP all: All messages in the selected mailbox
ResultadosObjeto<-Status of the delete operation

|

Descrição

A função .delete() sets the "deleted" flag for the messages defined in msgsIDs or allMsgs.

Pode passar:

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

Executing this function does not actually remove messages. Messages with the "delete" flag can still be found by the .searchMails() function. Flagged messages are deleted from the IMAP server with the .expunge() function or by selecting another mailbox or when the transporter object (created with IMAP New transporter) is destroyed.

Objeto devolvido

The function returns an object describing the IMAP status:

PropriedadeTipoDescrição
successBooleanoTrue if the operation is successful, False otherwise
statusTextTextStatus message returned by the IMAP server, or last error returned in the 4D error stack
errorsCollection4D error stack (not returned if a IMAP server response is received)
[].errcodeNúmero4D error code
[].messageTextDescription of the 4D error
[].componentSignatureTextSignature of the internal component which returned the error

Exemplo 1

To delete a selection of messages:

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

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

$transporter:=IMAP New transporter($server)

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

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

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

Exemplo 2

To delete all messages in the current mailbox:

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

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

$transporter:=IMAP New transporter($server)

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

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

.deleteBox()

Histórico
VersãoMudanças
v19Adicionado

.deleteBox( name : Text ) : Object

ParâmetrosTipoDescrição
nameText->Name of the mailbox to delete
ResultadosObjeto<-Status of the mailbox deletion operation

|

Descrição

A função .deleteBox() permanently removes the mailbox with the given name from the IMAP server. Attempting to delete an INBOX or a mailbox that does not exist will generate an error.

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

  • The function cannot delete a mailbox that has child mailboxes if the parent mailbox has the "\Noselect" attribute.
  • All messages in the deleted mailbox will also be deleted.
  • The ability to delete a mailbox depends on the mail server.

Objeto devolvido

The function returns an object describing the IMAP status:

PropriedadeTipoDescrição
successBooleanoTrue if the operation is successful, False otherwise
statusTextTextStatus message returned by the IMAP server, or last error returned in the 4D error stack
errorsCollection4D error stack (not returned if a IMAP server response is received)
[].errcodeNúmero4D error code
[].messageTextDescription of the 4D error
[].componentSignatureTextSignature of the internal component which returned the error

Exemplo

To delete the "Nova Orion Industries" child mailbox from the "Bills" mailbox hierarchy:

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

$options:=New object

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

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

$transporter:=IMAP New transporter($options)

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

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

.expunge()

Histórico
VersãoMudanças
v18 R6Adicionado

.expunge() : Object

ParâmetrosTipoDescrição
ResultadosObjeto<-Status of the expunge operation

|

Descrição

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

Objeto devolvido

The function returns an object describing the IMAP status:

PropriedadeTipoDescrição
successBooleanoTrue if the operation is successful, False otherwise
statusTextTextStatus message returned by the IMAP server, or last error returned in the 4D error stack
errorsCollection4D error stack (not returned if a IMAP server response is received)
[].errcodeNúmero4D error code
[].messageTextDescription of the 4D error
[].componentSignatureTextSignature of the internal component which returned the error

Exemplo

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

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

// Create transporter
$transporter:=IMAP New transporter($options)

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

// Find and delete all seen messages in INBOX
$ids:=$transporter.searchMails("SEEN")
$status:=$transporter.delete($ids)

// Purge all messages flagged as deleted
$status:=$transporter.expunge()

.getBoxInfo()

Histórico
VersãoMudanças
v18 R5name is optional

|v18 R4|Added|

.getBoxInfo( { name : Text }) : Object

ParâmetrosTipoDescrição
nameText->Name of the mailbox
ResultadosObjeto<-boxInfo object

|

Descrição

A função .getBoxInfo() returns a boxInfo object corresponding to the current maibox, or the mailbox name. > The function returns an empty BLOB if msgNumber or msgID designates a non-existing message, > If no mailbox is selected with the .selectBox() command, an error is generated, > If there is no open connection, .getMIMEAsBlob() will open a connection the last mailbox specified with .selectBox().

In the optional name parameter, pass the name of the mailbox to access. The name represents an unambiguous left-to-right hierarchy with levels separated by a specific delimiter character. The delimiter can be found with the .getDelimiter() function.

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

Objeto devolvido

O objeto boxInfo retornado contém as funcionalidades abaixo:

PropriedadeTipoDescrição
nametextName of the mailbox
mailCountnumberNúmero de mensagens na caixa de email
mailRecentnumberNumber of messages with the "recent" flag (indicating new messages)

Exemplo

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

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

.getBoxList()

Histórico
VersãoMudanças
v18 R4Adicionado
v19Add isSubscribed parameter

.getBoxList( { parameters : Object } ) : Collection

ParâmetrosTipoDescrição
parametersObjeto->Parameter object
ResultadosCollection<-Collection of mailbox objects

|

Descrição

A função .getBoxList() returns a collection of mailboxes describing all of the available mailboxes. This function allows you to locally manage the list of messages located on the IMAP mail server.

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

PropriedadeTipoDescrição
isSubscribedBooleano
  • True to return only subscribed mailboxes
  • False to return all available mailboxes
  • Resultados

    Each object of the returned collection contains the following properties:

    PropriedadeTipoDescrição
    [].nametextName of the mailbox
    [].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.

    If the account does not contain any mailboxes, an empty collection is returned.

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

    Exemplo

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

    $boxList:=$transporter.getBoxList()

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

    .getDelimiter()

    Histórico
    VersãoMudanças
    v18 R4Adicionado

    .getDelimiter() : Text

    ParâmetrosTipoDescrição
    ResultadosText<-Hierarchy delimiter character

    |

    Descrição

    A função .getDelimiter() returns the character used to delimit levels of hierarchy in the mailbox name.

    The delimiter is a character which can be used to:

    • create lower level (inferior) mailboxes
    • search higher or lower within the mailbox hierarchy

    Resultados

    Mailbox name delimiter character.

    Exemplo

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

    $boxList:=$transporter.getBoxList()

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

    .getMail()

    Histórico
    VersãoMudanças
    v18 R4Adicionado

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

    ParâmetrosTipoDescrição
    msgNumberInteger->Sequence number of the message
    msgIDText->ID única da mensagem
    optionsObjeto->Message handling instructions
    ResultadosObjeto<-Email object

    |

    Descrição

    A função .getMail() returns the Email object corresponding to the msgNumber or msgID in the mailbox designated by the IMAP_transporter. Essa função permite manejar localmente os conteúdos de email.

    In the first parameter, you can pass either:

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

    The optional options parameter allows you pass an object defining additional instructions for handling the message. As seguintes propriedades estão disponíveis:

    PropriedadeTipoDescrição
    updateSeenbooleanIf True, the message is marked as "seen" in the mailbox. If False, the message is not marked as "seen". Default value: True
    withBodybooleanPass True to return the body of the message. If False, only the message header is returned. Default value: True
    • The function generates an error and returns Null if msgID designates a non-existing message,
    • If no mailbox is selected with the .selectBox() function, an error is generated,
    • If there is no open connection, .getMail() will open a connection the last mailbox specified with .selectBox()`.

    Resultados

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

    Exemplo

    You want to get the message with ID = 1:

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

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

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

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

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

    .getMails()

    Histórico
    VersãoMudanças
    v18 R5Adicionado

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

    ParâmetrosTipoDescrição
    idsCollection->Collection of message ID
    startMsgInteger->Sequence number of the first message
    endMsgInteger->Sequence number of the last message
    optionsObjeto->Message handling instructions
    ResultadosObjeto<-Object containing:
    • a collection of Email objects and
    • a collection of IDs or numbers for missing messages, if any

    |

    Descrição

    A função .getMails() returns an object containing a collection of Email objects.

    First Syntax:

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

    The first syntax allows you to retrieve messages based on their IDs.

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

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

    Second syntax:

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

    The second syntax allows you to retrieve messages based on a sequential range. The values passed represent the position of the messages in the mailbox.

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

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

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

    Options

    PropriedadeTipoDescrição
    updateSeenBooleanoIf True, the specified messages are marked as "seen" in the mailbox. If False, the messages are not marked as "seen". Default value: True
    withBodyBooleanoPass True to return the body of the specified messages. If False, only the message headers are returned. Default value: True
    • If no mailbox is selected with the .selectBox() command, an error is generated.
    • If there is no open connection, .getMails() will open a connection the last mailbox specified with .selectBox().

    Resultados

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

    PropriedadeTipoDescrição
    listaCollectionCollection of Email objects. If no Email objects are found, an empty collection is returned.
    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

    You want to retrieve the 20 most recent emails without changing their "seen" status:

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

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

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

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

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

    .getMIMEAsBlob()

    Histórico
    VersãoMudanças
    v18 R4Adicionado

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

    ParâmetrosTipoDescrição
    msgNumberInteger->Sequence number of the message
    msgIDText->ID única da mensagem
    updateSeenBooleano->If True, the message is marked "seen" in the mailbox. If False the message is left untouched.
    ResultadosBLOB<-Blob of the MIME string returned from the mail server

    |

    Descrição

    A função .getMIMEAsBlob() returns a BLOB containing the MIME contents for the message corresponding to the msgNumber or msgID in the mailbox designated by the IMAP_transporter.

    In the first parameter, you can pass either:

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

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

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

    Resultados

    .getMIMEAsBlob() retorna um BLOB que pode ser arquivado em um banco de dados ou convertido a um objeto Email com o comando MAIL Convert from MIME.

    Exemplo

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

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

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

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

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

    .host

    Histórico
    VersãoMudanças
    v17 R5Adicionado

    .host : Text

    Descrição

    A propriedade .host contém o nome ou o endereço IP do servidor anfitrião. Utilizado para transacções postais (SMTP, POP3, IMAP).

    .logFile

    Histórico
    VersãoMudanças
    v17 R5Adicionado

    .logFile : Text

    Descrição

    A propriedade .logFile contém o caminho do arquivo de registo alargado definido (se existir) para a ligação de correio. Pode ser relativo (à pasta atual de Logs) ou absoluto.

    Ao contrário dos arquivos de registo regulares (ativados através do comando SET DATABASE PARAMETER ), os arquivos de registo armazenam o conteúdo MIME de todos os e-mails enviados e não têm qualquer limite de tamanho. Para mais informações sobre arquivos de registo estendidos, consultar:

    .move()

    Histórico
    VersãoMudanças
    v18 R5Adicionado

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

    ParâmetrosTipoDescrição
    msgsIDsCollection->Collection of message unique IDs (strings)
    allMsgsInteger->IMAP all: All messages in the selected mailbox
    destinationBoxText->Mailbox to receive moved messages
    ResultadosObjeto<-Status of the move operation

    |

    Descrição

    A função .move() moves the messages defined by msgsIDs or allMsgs to the destinationBox on the IMAP server.

    Pode passar:

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

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

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

    Objeto devolvido

    The function returns an object describing the IMAP status:

    PropriedadeTipoDescrição
    successBooleanoTrue if the operation is successful, False otherwise
    statusTextTextStatus message returned by the IMAP server, or last error returned in the 4D error stack
    errorsCollection4D error stack (not returned if a IMAP server response is received)
    [].errcodeNúmero4D error code
    [].messageTextDescription of the 4D error
    [].componentSignatureTextSignature of the internal component which returned the error

    Exemplo 1

    To move a selection of messages:

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

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

    $transporter:=IMAP New transporter($server)

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

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

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

    Exemplo 2

    To move all messages in the current mailbox:

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

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

    $transporter:=IMAP New transporter($server)

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

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

    .numToID()

    Histórico
    VersãoMudanças
    v18 R5Adicionado

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

    ParâmetrosTipoDescrição
    startMsgInteger->Sequence number of the first message
    endMsgInteger->Sequence number of the last message
    ResultadosCollection<-Collection of unique IDs

    |

    Descrição

    A função .numToID() converts the sequence numbers to IMAP unique IDs for the messages in the sequential range designated by startMsg and endMsg in the currently selected mailbox.

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

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

    Resultados

    The function returns a collection of strings (unique IDs).

    Exemplo

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

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

    $transporter:=IMAP New transporter($server)

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

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

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

    .removeFlags()

    Histórico
    VersãoMudanças
    v18 R6Adicionado

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

    ParâmetrosTipoDescrição
    msgIDsCollection->Collection of strings: Message unique IDs (text)
    Text: Unique ID of a message
    Longint (IMAP all): All messages in the selected mailbox
    keywordsObjeto->Keyword flags to remove
    ResultadosObjeto<-Status of the removeFlags operation

    |

    Descrição

    A função .removeFlags() removes flags from the msgIDs for the specified keywords.

    In the msgIDs parameter, you can pass either:

    • a collection containing the unique IDs of specific messages or

    • the unique ID (text) of a single message or

    • the following constant (longint) for all messages in the selected mailbox:

      ConstanteValueComentário
      IMAP all1Select all messages in the selected mailbox

    The keywords parameter lets you pass an object with keyword values for specific flags to remove from msgIDs. You can pass any of the following keywords:

    ParâmetrosTipoDescrição
    $draftBooleanoTrue to remove the "draft" flag from the message
    $seenBooleanoTrue to remove the "seen" flag from the message
    $flaggedBooleanoTrue to remove the "flagged" flag from the message
    $answeredBooleanoTrue to remove the "answered" flag from the message
    $deletedBooleanoTrue to remove the "deleted" flag from the message

    Note that False values are ignored.

    Objeto devolvido

    The function returns an object describing the IMAP status:

    PropriedadeTipoDescrição
    successBooleanoTrue if the operation is successful, False otherwise
    statusTextTextStatus message returned by the IMAP server, or last error returned in the 4D error stack
    errorsCollection4D error stack (not returned if a IMAP server response is received)
    [].errcodeNúmero4D error code
    [].messageTextDescription of the 4D error
    [].componentSignatureTextSignature of the internal component which returned the error

    Exemplo

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

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

    // Create transporter
    $transporter:=IMAP New transporter($options)

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

    // Mark all messages from INBOX as unseen
    $flags:=New object
    $flags["$seen"]:=True
    $status:=$transporter.removeFlags(IMAP all;$flags)

    .renameBox()

    Histórico
    VersãoMudanças
    v19Adicionado

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

    ParâmetrosTipoDescrição
    currentNameText->Name of the current mailbox
    newNameText->New mailbox name
    ResultadosObjeto<-Status of the renaming operation

    |

    Descrição

    A função .renameBox() changes the name of a mailbox on the IMAP server. Attempting to rename a mailbox from a mailbox name that does not exist or to a mailbox name that already exists will generate an error.

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

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

    Objeto devolvido

    The function returns an object describing the IMAP status:

    PropriedadeTipoDescrição
    successBooleanoTrue if the operation is successful, False otherwise
    statusTextTextStatus message returned by the IMAP server, or last error returned in the 4D error stack
    errorsCollection4D error stack (not returned if a IMAP server response is received)
    [].errcodeNúmero4D error code
    [].messageTextDescription of the 4D error
    [].componentSignatureTextSignature of the internal component which returned the error

    Exemplo

    To to rename your “Invoices” mailbox to “Bills”:

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

    $options:=New object

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

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

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

    $transporter:=IMAP New transporter($options)

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

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

    .port

    Histórico
    VersãoMudanças
    v17 R4Adicionado

    .port : Integer

    Descrição

    A propriedade .port contém o número do porto utilizado para as transações postais. Por padrão, se a propriedade não tiver sido definida no objeto servidor (utilizado para criar o objecto transportador com SMTP Novo transportador, POP3 Novo transportador, ou IMAP Novo transportador), o valor é 30:

    • SMTP - 587
    • POP3 - 995
    • IMAP - 993

    .searchMails()

    Histórico
    VersãoMudanças
    v18 R5Adicionado

    .searchMails( searchCriteria : Text ) : Collection

    ParâmetrosTipoDescrição
    searchCriteriaText->Critérios de pesquisa
    ResultadosCollection<-Collection of message numbers

    |

    Descrição

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

    A função .searchMails() searches for messages that match the given searchCriteria in the current mailbox. searchCriteria consists of one or more search keys.

    searchCriteria is a text parameter listing one or more search keys (see Authorized search-keys below) associated or not with values to look for. A search key may be a single or multiple items. Por exemplo:

    SearchKey1 = FLAGGED SearchKey2 = NOT FLAGGED SearchKey3 = FLAGGED DRAFT

    Matching is usually not case-sensitive

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

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

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

    ... returns all messages with \Seen flag set OR \Flagged flag set

    searchCriteria = NOT SEEN

    ... returns all messages with \Seen flag not set.

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

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

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

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

    As concerns the last two examples, notice that the result of the search is different when you remove the parentheses of the first search key list.

    • The searchCriteria may include the optional [CHARSET] specification. This consists of the "CHARSET" word followed by a registered [CHARSET] (US ASCII, ISO-8859). It indicates the charset of the searchCriteria string. Therefore, you must convert the searchCriteria string into the specified charset if you use the [CHARSET] specification (see the CONVERT FROM TEXT or Convert to text commands). By default, 4D encodes in Quotable Printable the searchCriteria string if it contains extended characters.
    searchCriteria = CHARSET "ISO-8859" BODY "Help"

    ... means the search criteria uses the charset iso-8859 and the server will have to convert the search criteria before searching, if necessary.

    Search value types

    Search-keys may request the value to search for:

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

    • Search-keys with a string value: the string may contain any character and must be quoted. If the string does not contain any special characters, like the space character for instance, it does not need to be quoted. Quoting such strings will ensure that your string value will be correctly interpreted. Example: searchCriteria = FROM "SMITH" For all search keys that use strings, a message matches the key if the string is a substring of the field. Matching is not case-sensitive.

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

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

    • Search-keys with a message set value: Identifies a set of messages. For message sequence numbers, these are consecutive numbers from 1 to the total number of messages in the mailbox. A comma delimits individual numbers; a colon delimits between two numbers inclusive. Examples: 2,4:7,9,12:* 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.

    Authorized search-keys

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

    .selectBox()

    Histórico
    VersãoMudanças
    v18 R4Adicionado

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

    ParâmetrosTipoDescrição
    nameText->Name of the mailbox
    stateInteger->Mailbox access status
    ResultadosObjeto<-boxInfo object

    |

    Descrição

    A função .selectBox() selects the name mailbox as the current mailbox. Essa função permite que recupere informação sobre o mailbox.

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

    In the name parameter, pass the name of the mailbox to access. The name represents an unambiguous left-to-right hierarchy with levels separated by a specific delimiter character. The delimiter can be found with the .getDelimiter() function.

    The optional state parameter defines the type of access to the mailbox. The possible values are:

    ConstanteValueComentário
    IMAP read only state1The selected mailbox is accessed with read only privileges. Messages with a "recent" flag (indicating new messages) remain unchanged.
    IMAP read write state0The selected mailbox is accessed with read and write privileges. Messages are considered "seen" and lose the "recent" flag (indicating new messages). (Valor padrão)
    • The function generates an error and returns Null if name designates a non-existing mailbox.
    • If there is no open connection, .selectBox() will open a connection.
    • If the connection has not been used since the designated connection delay (see IMAP New transporter), the .checkConnection() function is automatically called.

    Objeto devolvido

    O objeto boxInfo retornado contém as funcionalidades abaixo:

    PropriedadeTipoDescrição
    nameTextName of the mailbox
    mailCountnumberNúmero de mensagens na caixa de email
    mailRecentnumberNumber of messages with the "recent" flag

    Exemplo

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

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

    .subscribe()

    Histórico
    VersãoMudanças
    v19Adicionado

    .subscribe( name : Text ) : Object

    ParâmetrosTipoDescrição
    nameText->Name of the mailbox
    ResultadosObjeto<-Status of the subscribe operation

    |

    Descrição

    A função .subscribe() allows adding or removing of the specified mailbox to/from the IMAP server’s set of “subscribed” mailboxes. As such, you can choose to narrow down a large list of available mailboxes by subscribing to those you usually want to see.

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

    Objeto devolvido

    The function returns an object describing the IMAP status:

    PropriedadeTipoDescrição
    successBooleanoTrue if the operation is successful, False otherwise
    statusTextTextStatus message returned by the IMAP server, or last error returned in the 4D error stack
    errorsCollection4D error stack (not returned if a IMAP server response is received)
    [].errcodeNúmero4D error code
    [].messageTextDescription of the 4D error
    [].componentSignatureTextSignature of the internal component which returned the error

    Exemplo

    To subscribe to the "Atlas Corp” mailbox in the "Bills" hierarchy:

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

    $options:=New object

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

    $transporter:=IMAP New transporter($options)

    $name:="Bills"+$transporter.getDelimiter()+"Atlas Corp"
    $status:=$transporter.subscribe($name) If ($status.success)
    ALERT("Mailbox subscription successful!")
    Else
    ALERT("Error: "+$status.statusText)
    End if
    Else
    ALERT("Error: "+$status.statusText)
    End if
    End if

    .unsubscribe()

    Histórico
    VersãoMudanças
    v19Adicionado

    .unsubscribe( name : Text ) : Object

    ParâmetrosTipoDescrição
    nameText->Name of the mailbox
    ResultadosObjeto<-Status of the unsubscribe operation

    |

    Descrição

    A função .unsubscribe() removes a mailbox from a set of subscribed mailboxes. This allows you reduce the number of mailboxes you usually see.

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

    Objeto devolvido

    The function returns an object describing the IMAP status:

    PropriedadeTipoDescrição
    successBooleanoTrue if the operation is successful, False otherwise
    statusTextTextStatus message returned by the IMAP server, or last error returned in the 4D error stack
    errorsCollection4D error stack (not returned if a IMAP server response is received)
    [].errcodeNúmero4D error code
    [].messageTextDescription of the 4D error
    [].componentSignatureTextSignature of the internal component which returned the error

    Exemplo

    To unsubscribe from the "Atlas Corp” mailbox in the "Bills" hierarchy:

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

    $options:=New object

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

    $transporter:=IMAP New transporter($options)

    $name:="Bills"+$transporter.getDelimiter()+"Atlas Corp"
    $status:=$transporter.unsubscribe($name) If ($status.success)
    ALERT("Mailbox unsubscription successful!")
    Else
    ALERT("Error: "+$status.statusText)
    End if
    Else
    ALERT("Error: "+$status.statusText)
    End if
    End if

    .user

    Histórico
    VersãoMudanças
    v17 R4Adicionado

    .user : Text

    Descrição

    A propriedade .user contém o nome de usuário utilizado para autenticação no servidor de correio.