Objet InboundEmail
Pour chaque e-mail reçu par le domaine de service de messagerie électronique Apex, Salesforce crée un objet InboundEmail distinct qui comporte le contenu et les pièces jointes de cet e-mail. Vous pouvez utiliser des classes Apex qui implémentent l'interface Messaging.InboundEmailHandler pour gérer un e-mail entrant. En utilisant la méthode handleInboundEmail dans cette classe vous pouvez accéder à un objet InboundEmail pour récupérer le contenu, les en-têtes et les pièces jointes des e-mails entrants, et exécuter de nombreuses fonctions.
Éditions requises
| Disponible avec : Salesforce Classic (pas disponible dans toutes les organisations) |
| Disponible avec : Enterprise Edition, Performance Edition, Unlimited Edition et Developer Edition |
Exemple 1 : Créer des tâches pour les contacts
L'exemple suivant vous montre comment rechercher un contact à l'aide de l'adresse de l'e-mail entrant et créer une nouvelle tâche.
public with sharing class CreateTaskEmailExample implements Messaging.InboundEmailHandler {
public Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email,
Messaging.InboundEnvelope env){
// Create an InboundEmailResult object for returning the result of the
// Apex Email Service
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
String myPlainText= '';
// Add the email plain text into the local variable
myPlainText = email.plainTextBody;
// New Task object to be created
Task[] newTask = new Task[0];
// Try to look up any contacts based on the email from address
// If there is more than one contact with the same email address,
// an exception will be thrown and the catch statement will be called.
try {
Contact vCon = [SELECT Id, Name, Email
FROM Contact
WHERE Email = :email.fromAddress
WITH USER_MODE
LIMIT 1 ];
// Add a new Task to the contact record we just found above.
newTask.add(new Task(Description = myPlainText,
Priority = 'Normal',
Status = 'Inbound Email',
Subject = email.subject,
IsReminderSet = true,
ReminderDateTime = System.now()+1,
WhoId = vCon.Id));
// Insert the new Task
insert as user newTask;
System.debug('New Task Object: ' + newTask );
}
// If an exception occurs when the query accesses
// the contact record, a QueryException is called.
// The exception is written to the Apex debug log.
catch (QueryException e) {
System.debug('Query Issue: ' + e);
}
// Set the result to true. No need to send an email back to the user
// with an error message
result.success = true;
// Return the result for the Apex Email Service
return result;
}
}Exemple 2 : Gérer les e-mails de désabonnement
Des entreprises qui envoient des e-mails de marketing à leurs clients et à leurs clients potentiels doivent fournir aux destinataires un moyen de désabonnement. Vous trouverez ci-dessous un exemple de la façon dont un service de messagerie électronique peut traiter les demandes de désabonnement. Le code recherche le mot « désabonnement » dans la ligne de l'objet de l'e-mail entrant. Si le mot est trouvé, le code trouve tous les contacts et les pistes qui correspondent à l'adresse e-mail De et définit le champ Désinscription des e-mails (HasOptedOutOfEmail) sur True.
public with sharing class unsubscribe implements Messaging.inboundEmailHandler{
public Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,
Messaging.InboundEnvelope env ) {
// Create an inboundEmailResult object for returning
// the result of the email service.
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
// Create contact and lead lists to hold all the updated records.
List<Contact> lc = new List <contact>();
List<Lead> ll = new List <lead>();
// Convert the subject line to lower case so the program can match on lower case.
String mySubject = email.subject.toLowerCase();
// The search string used in the subject line.
String s = 'unsubscribe';
// Check the variable to see if the word "unsubscribe" was found in the subject line.
Boolean unsubMe;
// Look for the word "unsubcribe" in the subject line.
// If it is found, return true; otherwise, return false.
unsubMe = mySubject.contains(s);
// If unsubscribe is found in the subject line, enter the IF statement.
if (unsubMe == true) {
try {
// Look up all contacts with a matching email address.
for (Contact c : [SELECT Id, Name, Email, HasOptedOutOfEmail
FROM Contact
WHERE Email = :env.fromAddress
AND hasOptedOutOfEmail = false
LIMIT 100]) {
// Add all the matching contacts into the list.
c.hasOptedOutOfEmail = true;
lc.add(c);
}
// Update all of the contact records.
update as user lc;
}
catch (System.QueryException e) {
System.debug('Contact Query Issue: ' + e);
}
try {
// Look up all leads matching the email address.
for (Lead l : [SELECT Id, Name, Email, HasOptedOutOfEmail
FROM Lead
WHERE Email = :env.fromAddress
AND isConverted = false
AND hasOptedOutOfEmail = false
LIMIT 100]) {
// Add all the leads to the list.
l.hasOptedOutOfEmail = true;
ll.add(l);
System.debug('Lead Object: ' + l);
}
// Update all lead records in the query.
update as user ll;
}
catch (System.QueryException e) {
System.debug('Lead Query Issue: ' + e);
}
System.debug('Found the unsubscribe word in the subject line.');
}
else {
System.debug('No Unsuscribe word found in the subject line.' );
}
// Return True and exit.
// True confirms program is complete and no emails
// should be sent to the sender of the unsubscribe request.
result.success = true;
return result;
}
}@isTest
private class unsubscribeTest {
// The following test methods provide adequate code coverage
// for the unsubscribe email class.
// There are two methods, one that does the testing
// with a valid "unsubcribe" in the subject line
// and one the does not contain "unsubscribe" in the
// subject line.
static testMethod void testUnsubscribe() {
// Create a new email and envelope object.
Messaging.InboundEmail email = new Messaging.InboundEmail() ;
Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
// Create a new test lead and insert it in the test method.
Lead l = new lead(firstName='John',
lastName='Smith',
Company='Salesforce',
Email='user@acme.com',
HasOptedOutOfEmail=false);
insert l;
// Create a new test contact and insert it in the test method.
Contact c = new Contact(firstName='john',
lastName='smith',
Email='user@acme.com',
HasOptedOutOfEmail=false);
insert c;
// Test with the subject that matches the unsubscribe statement.
email.subject = 'test unsubscribe test';
env.fromAddress = 'user@acme.com';
// Call the class and test it with the data in the testMethod.
unsubscribe unsubscribeObj = new unsubscribe();
unsubscribeObj.handleInboundEmail(email, env );
}
static testMethod void testUnsubscribe2() {
// Create a new email and envelope object.
Messaging.InboundEmail email = new Messaging.InboundEmail();
Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
// Create a new test lead and insert it in the test method.
Lead l = new lead(firstName='john',
lastName='smith',
Company='Salesforce',
Email='user@acme.com',
HasOptedOutOfEmail=false);
insert l;
// Create a new test contact and insert it in the test method.
Contact c = new Contact(firstName='john',
lastName='smith',
Email='user@acme.com',
HasOptedOutOfEmail=false);
insert c;
// Test with a subject that does not contain "unsubscribe."
email.subject = 'test';
env.fromAddress = 'user@acme.com';
// Call the class and test it with the data in the test method.
unsubscribe unsubscribeObj = new unsubscribe();
unsubscribeObj.handleInboundEmail(email, env );
}
}Objet InboundEmail
Un objet InboundEmail comporte les champs suivants.
Objet InboundEmail.Header
Un objet InboundEmail stocke les informations d'en-tête d'e-mail RFC 2822 dans un objet Inbound.HeaderObject avec les champs suivants.
| Nom | Type | Description |
|---|---|---|
| name | Chaîne | Le nom du paramètre d'en-tête, par exemple Date ou Message-ID. |
| value | Chaîne | Valeur de l'en-tête. |
Objet InboundEmail.BinaryAttachment
Un objet InboundEmail stocke les pièces jointes binaires dans un objet InboundEmail.BinaryAttachment.
Parmi les pièces jointes binaires, on trouve des fichiers image, audio, vidéo et des fichiers d'application.
Un objet InboundEmail.BinaryAttachment possède les champs suivants.
| Nom | Type | Description |
|---|---|---|
| body | Blob | Corps de la pièce jointe. |
| fileName | Chaîne | Nom du fichier joint. |
| mimeTypeSubType | Chaîne | Type MIME principal et secondaire. |
Objet InboundEmail.TextAttachment
Un objet InboundEmail stocke le texte joint dans un objet InboundEmail.TextAttachment.
Les pièces jointes peuvent être les suivantes :
- Pièces jointes avec un type de
textMIME (Multipurpose Internet Mail Extension) - Pièces jointes avec un type MIME
application/octet-streamet un nom de fichier qui finit par une extension.vcf ou .vcs. Ils sont respectivement enregistrés sous les types MIMEtext/x-vcardettext/calendar.
Un objet InboundEmail.TextAttachment possède les champs suivants.
Objet InboundEmailResult
L'objet InboundEmailResult sert à renvoyer le résultat du service de messagerie électronique. Si l'objet est nul, le résultat est supposé réussi. Un objet InboundEmailResult comporte les champs suivants.
Objet InboundEnvelope
L'objet InboundEnvelope stocke l'information d'enveloppe associée à l'e-mail entrant et possède les champs suivants.
| Nom | Type | Description |
|---|---|---|
| toAddress | Chaîne | Nom qui apparaît dans le champ À de l'enveloppe, le cas échéant. |
| fromAddress | Chaîne | Nom qui apparaît dans le champ À de l'enveloppe, le cas échéant. |

