function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
adiazadiaz 

Email to Custom Object

Is it possible to have an email service apex that will update an existing record in a custom object? I'm not a coder but would really appreciate it if someone can guide me to a similar code I can use to develop this functionality. Thanks!

Best Answer chosen by Admin (Salesforce Developers) 
David81David81

Should certainly be possible.  Have a look at 

http://www.salesforce.com/us/developer/docs/apexcode/index_Left.htm#StartTopic=Content/apex_classes_email_inbound_using.htm

 

The docs give a basic example of processing inbound emails. Feel free to ask more if you get stuck.

All Answers

David81David81

Should certainly be possible.  Have a look at 

http://www.salesforce.com/us/developer/docs/apexcode/index_Left.htm#StartTopic=Content/apex_classes_email_inbound_using.htm

 

The docs give a basic example of processing inbound emails. Feel free to ask more if you get stuck.

This was selected as the best answer
adiazadiaz

You are the man! Thanks! I got my code up and running. 

adiazadiaz

I have my code working as originally planned. Now I would like to take it a step further and have the attachments on the email be attached to the record.  I have followed step by step as shown on this sample code to get the attachment onto salesforce via my email apex. I even tried the exact code on the web to test and it still would not work. The email service looks right (just as shown on the link below). Feedback is appreciated.

 

http://wiki.developerforce.com/index.php/An_Introduction_To_Email_Services_on_Force.com

David81David81

Can you post the code you have working now? If it does everything except insert the attachments, it may be an easy fix.

adiazadiaz
Sure. Everything else works; it creates an account if it doesn't find it and attaches the body of the email as a note. It just doesn't process attachments. I've tried a txt attachment and a binary as well. I've attached the code i used for testing: global class EmailToSalesForce implements Messaging.InboundEmailHandler { global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.Inboundenvelope envelope) { Account account; Messaging.InboundEmailResult result = new Messaging.InboundEmailResult(); try { // Look for account whose name is the subject and create it if necessary if ([select count() from Account where Name =:email.subject] == 0) { account = new Account(); account.Name = email.subject; insert account; } else { account = [select Id from Account where Name =:email.subject]; } // Convert cc'd addresses to contacts for (String address: email.ccAddresses) { Contact contact = new Contact(); Matcher matcher = Pattern.compile('<.+>').matcher(address); // Parse addresses to names and emails if (matcher.find()) { String[] nameParts = address.split('[ ]*<.+>')[0].replace('"', '').split('[ ]+'); contact.FirstName = nameParts.size() > 1? nameParts[0]: ''; contact.LastName = nameParts.size() > 1? nameParts[nameParts.size()-1]: nameParts[0]; contact.Email = matcher.group().replaceAll('[<>]', ''); } else { contact.LastName = address; contact.Email = address; } // Add if new if ([select count() from Contact where Email =:contact.Email] == 0) { contact.AccountId = account.Id; insert contact; } } // Turn email body into note Note note = new Note(); note.Title = email.fromName + ' (' + DateTime.now() + ')'; note.Body = email.plainTextBody; note.ParentId = account.Id; insert note; // Save attachments, if any for (Messaging.Inboundemail.TextAttachment tAttachment :email.textAttachments) { Attachment attachment = new Attachment(); attachment.Name = tAttachment.fileName; attachment.Body = Blob.valueOf(tAttachment.body); attachment.ParentId = account.Id; insert attachment; } for (Messaging.Inboundemail.BinaryAttachment bAttachment :email.binaryAttachments) { Attachment attachment = new Attachment(); attachment.Name = bAttachment.fileName; attachment.Body = bAttachment.body; attachment.ParentId = account.Id; insert attachment; } result.success = true; result.message = (email.subject + ' matched'); } catch (Exception e) { result.success = false; result.message = 'Oops, I failed.'; } return result; } }
David81David81

Any chance you could repost that in a code block? It's a tad bit hard to read that as is...

adiazadiaz

Oops...Sorry about that:

 

 

 

global class EmailToSalesForce implements Messaging.InboundEmailHandler {
  global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, 
                                                         Messaging.Inboundenvelope envelope) {
  
Account account;
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();

try {



// Look for account whose name is the subject and create it if necessary
if ([select count() from Account where Name =:email.subject] == 0) {
  account = new Account();
  account.Name = email.subject;
  insert account;
} else {
  account = [select Id from Account where Name =:email.subject];
}


// Convert cc'd addresses to contacts
for (String address: email.ccAddresses) {
  Contact contact = new Contact();
  Matcher matcher = Pattern.compile('<.+>').matcher(address);
 
  // Parse addresses to names and emails
  if (matcher.find()) {
    String[] nameParts = address.split('[ ]*<.+>')[0].replace('"', '').split('[ ]+');
   
    contact.FirstName = nameParts.size() > 1? nameParts[0]: '';
    contact.LastName = nameParts.size() > 1? nameParts[nameParts.size()-1]: nameParts[0];
    contact.Email = matcher.group().replaceAll('[<>]', '');
  } else {
    contact.LastName = address;
    contact.Email = address;
  }
 
  // Add if new
  if ([select count() from Contact where Email =:contact.Email] == 0) {
    contact.AccountId = account.Id;
    insert contact;
  }
}


// Turn email body into note
Note note = new Note();

note.Title = email.fromName + ' (' + DateTime.now() + ')';
note.Body = email.plainTextBody;
note.ParentId = account.Id;
insert note;




// Save attachments, if any
for (Messaging.Inboundemail.TextAttachment  tAttachment :email.textAttachments) {
  Attachment attachment = new Attachment();
 
  attachment.Name = tAttachment.fileName;
  attachment.Body = Blob.valueOf(tAttachment.body);
  attachment.ParentId = account.Id;
  insert attachment;
}
for (Messaging.Inboundemail.BinaryAttachment  bAttachment :email.binaryAttachments) {
  Attachment attachment = new Attachment();
 
  attachment.Name = bAttachment.fileName;
  attachment.Body = bAttachment.body;
  attachment.ParentId = account.Id;
  insert attachment;
}

      
      result.success = true;
      result.message = (email.subject + ' matched');
    } catch (Exception e) {
      result.success = false;
      result.message = 'Oops, I failed.';
    }
   
    return result;
  }
}

 

 

David81David81

I'd make sure your email service setup is allowing attachments. Sounds silly, I know, but I always go to the easy stuff first. If it is, then I'd put some debug statements in your for loop to make sure you are actually getting the attachments list in your code.

adiazadiaz

Everything looks good on the email service. It's enabled to receive all attachments. Would you mind sharing a debug statement that would fit my code? Thanks!

Gorka AmianGorka Amian
Hi all,

Jumping here now. I have a similar issue (although I don't need to archive the attachements), and I can't access David81 link from up top. It just takes me to an "Introducing Apex" page. Can I get any help? This is what I am trying to do:

I have a custom object (called "Users") that holds our software end users, whom we continuously email. I would like to attach the emails to their activity history when we bcc salesforce, just like it happens for leads and contacts.

Is this possible, can anybody help?

Thanks!
llisallisa
hello adiaz,
i am trying to attach a csv file through email service but your code is not working.it gives an error like " Oops, I failed."
Simon Ekholm 1Simon Ekholm 1
Davids link is not working properly, here is the same page but with a new URL https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_inbound_using.htm