Monthly Archives: October 2011

HOW TO: Create A Salesforce Email And Associate It To An Opportunity

The Salesforce developer site describes the email object as having a whatId property which you can use to associate to a property. This specific property is commented as only working if you set a target targetObjectId which can be set to the contact the opportunity was created for. In my specific case, I decided to create a .NET mail object and transform it into a SingleMailMessage to associate to an opportunity. The final result looked something like this:

Public Sub SendEmailForOpportunity(ByVal Email As Net.Mail.MailMessage, ByVal OpportunityId As String)
        Dim semSingleEmailMessage As SalesForceEnterprise.SingleEmailMessage
        Dim lstEmails As List(Of String)
        Dim lstMessages As List(Of SalesForceEnterprise.SingleEmailMessage)
        Try
            SetupService()
            semSingleEmailMessage = New SalesForceEnterprise.SingleEmailMessage
            If Email.Bcc IsNot Nothing Then
                lstEmails = New List(Of String)
                For Each maoMailAddress As MailAddress In Email.Bcc
                    lstEmails.Add(maoMailAddress.Address)
                Next
                semSingleEmailMessage.bccAddresses = lstEmails.ToArray
            End If
            If Email.CC IsNot Nothing Then
                lstEmails = New List(Of String)
                For Each maoMailAddress As MailAddress In Email.CC
                    lstEmails.Add(maoMailAddress.Address)
                Next
                semSingleEmailMessage.ccAddresses = lstEmails.ToArray
            End If
            If Email.ReplyTo IsNot Nothing Then
                semSingleEmailMessage.replyTo = Email.ReplyTo.Address
                semSingleEmailMessage.senderDisplayName = Email.ReplyTo.DisplayName
            End If
            If Email.To IsNot Nothing Then
                lstEmails = New List(Of String)
                For Each maoMailAddress As MailAddress In Email.To
                    lstEmails.Add(maoMailAddress.Address)
                Next
                semSingleEmailMessage.toAddresses = lstEmails.ToArray
            End If
            semSingleEmailMessage.htmlBody = Email.Body
            semSingleEmailMessage.subject = Email.Subject
            semSingleEmailMessage.whatId = OpportunityId
            lstMessages = New List(Of SalesForceEnterprise.SingleEmailMessage)
            lstMessages.Add(semSingleEmailMessage)
            SalesForceService.sendEmail(lstMessages.ToArray)
        Catch ex As Exception
            Throw New Exception("Failure during sending email", ex)
        End Try
    End Sub

The SetupService method logs into the service and passes in the necessary credentials just like the standard Salesforce API recommends.