salesforce 零基础学习(六十七)SingleEmailMessage 那点事

 在salesforce开发中,发送邮件是一个很常见的功能。比如在进入审批流以后的通过和拒绝的操作需要发送邮件给记录的owner,和其他系统交互以后更改了某些状态通知相关的User或者Contact等等。可以说,发送邮件在业务上是一个必不可少的环节。

salesforce提供了多种发送邮件的方式,比如SingleEmail,MassEmail,这里主要说一下SingleEmail.

SingleEmail操作位于Messaging.SingleEmailMessage类中,主要有两种方式发送邮件,一个是可以通过模板,一个是不需要借助模板。这里主要说一下相关主要方法:

  • public Void setToAddresses(String[] toAddresses):设置接收人的email地址;
  • public Void setCcAddresses(String[] ccAddresses):设置抄送人的email地址;
  • public Void setBccAddresses(String[] bccAddresses):设置私密抄送人的email地址;
  • public Void setCharset(String characterSet):设置email的内容的编码;
  • public Void setTargetObjectId(ID targetObjectId):当使用email template时,此方法是必须使用的。ID可以为contact/lead/user.默认email会发送此ID。而且使用此方法发送邮件,不会使email limit 加1,所以如果只是给org内部的user或者contact发送,可以使用此种方式减少一些相关限制。
  • public Void setSaveAsActivity(Boolean saveAsActivity):如果设置了targetObjectId,则需要对它赋值为false,默认为true;
  • public void setTreatTargetObjectAsRecipient(Boolean treatAsRecipient):设置targetObjectId是否作为接收人接收此邮件,默认是true,如果不想将targetObjectId作为接收人,则设置为false;
  • public Void setPlainTextBody(String plainTextBody):设置邮件body内容,如果body内容为普通的文本;
  • public Void setSubject(String subject):设置邮件标题;
  • public void setEntityAttachments(List<String> ids):设置邮件的附件,参数可以传递document ids;
  • public Void setTemplateId(ID templateId):设置email的template,可以通过模板发送相关邮件,如果使用email的template并且里面没有相关的format,可以不用设置body和subject;
  • public Void setHtmlBody(String htmlBody):设置邮件的body,如果body内容为html内容;
  • public Void setWhatId(ID whatId):如果template中使用了merge field,可以指定需要引用的object的ID,比如模板中使用了{!Account.Name},则需要设置whatId项为account的ID;
  • public Void setSenderDisplayName(String displayName):设置邮件的发件人的显示名称;
  • public Void setReplyTo(String replyAddress):设置接收人回复邮件的email地址;

其他方法可以自行查看。下面内容为不使用模板和使用模板demo.

一.不使用邮件模板

1.发送普通文本邮件:此方法会发送邮件给targetObjectId设置的User/Contact/lead对应的email地址

  public void sendEmailWithoutEmailTemplateToOrgUsers() {
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setSenderDisplayName('the sender name you want to show');
        email.setPlainTextBody('test email text');
        email.setSubject('test email subject');
        email.setTargetObjectId('00528000002MLtt');//使用此种方式给org内部User/Contact/Lead发邮件,email limit的count不加1
        email.setSaveAsActivity(false);//如果设置targetObjectId,则必须设置setSaveAsActivity为false
        Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{email});
    }

2.发送html格式邮件:发送html格式邮件给toAddresses的user

    public void sendEmailWithoutEmailTemplateToExtraUser() {
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setSenderDisplayName('the sender name you want to show');
        email.setHtmlBody('<span color="red">测试html body内容</span>');
        email.setSubject('test email subject use html');
        //addresses which you wanna send to
        List<String> toAddresses = new List<String>();
        toAddresses.add('xx@qq.com');
        email.setToAddresses(toAddresses);
        Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{email});
    }

二.使用邮件模板

邮件的template  salesforce提供了4种类型方式:Text/HTML (using Letterhead)/Custom (without using Letterhead)/Visualforce

使用模板方式在发送邮件中使用很多,可以在setup->搜索email template即可设置email template.

1.Text类型template,使用merge field:使用merge field,需要在程序中引用相关的template并且设置相关引用的object设置给whatId.

 

 

 

    public void sendEmailWithTextTemplateUseMergeField() {
        EmailTemplate temp =  [
            SELECT Id, Name, Subject, HtmlValue, Body, BrandTemplateId
            FROM EmailTemplate
            WHERE DeveloperName = 'Test_Text_With_Merge_Field'
            LIMIT 1
        ];
        Contact con = [SELECT Id FROM Contact where name = 'york zhang'];
        Goods__c goods = [select Id,GoodsName__c from Goods__c where GoodsName__c != null limit 1];
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

        //set display name,the value will show sender name
        email.setSenderDisplayName('the sender name you want to show');

        //if use template,targetObjectId will be required
        email.setTargetObjectId(con.Id);

        //for default,the email will send to targetObject's email,
        //if you don't want to send target object (user/contact/lead),just setTreatTargetObjectAsRecipient false 
        email.setTreatTargetObjectAsRecipient(false);

        //if target object id is user or contact,set saveAsActivity false
        email.setSaveAsActivity(false);

        //set merge object id only if target object instanceof contact
        email.setWhatId(goods.Id);

        //set template id
        email.setTemplateId(temp.Id);
        
        List<String> toAddresses = new List<String>{'xx@qq.com'};
        email.setToAddresses(toAddresses);
        Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{email});
    }

2.Text类型template使用format:如果有些地方参数希望程序动态传入,可以使用format方式传入,html类型也可以使用,下面不做解释;

    public void sendEmailWithTextTemplateUseFormat() {
        EmailTemplate temp =  [
            SELECT Id, Name, Subject, HtmlValue, Body, BrandTemplateId
            FROM EmailTemplate
            WHERE DeveloperName = 'Test_Text_With_Format'
            LIMIT 1
        ];
        String subjectFormat = String.format(temp.Subject, new List<String>{'test subject title'});
        String bodyFormat = String.format(temp.Body,new List<String>{'test param1','test param2'});
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        Contact con = [SELECT Id FROM Contact where name = 'york zhang'];
        email.setTargetObjectId(con.Id);
        email.setSaveAsActivity(false);
        email.setSubject(subjectFormat);
        email.setPlainTextBody(bodyFormat);
        email.setTemplateId(temp.Id);
        Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{email});
    }

3.Html类型template:使用html template写内容的时候可以将meta倒下来写好html以后在deploy上去

 

    public void sendEmailWithHtmlTemplateUseFormat() {
        EmailTemplate temp =  [
            SELECT Id, Name, Subject, HtmlValue, Body, BrandTemplateId
            FROM EmailTemplate
            WHERE DeveloperName = 'Test_Text_With_Html'
            LIMIT 1
        ];

        String subjectFormat = String.format(temp.Subject, new List<String>{'test subject title'});
        String bodyFormat = String.format(temp.HtmlValue,new List<String>{'test param1','test param2'});
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        Contact con = [SELECT Id FROM Contact where name = 'york zhang'];
        email.setTargetObjectId(con.Id);
        email.setSaveAsActivity(false);
        email.setSubject(subjectFormat);
        email.setHtmlBody(bodyFormat);
        email.setTemplateId(temp.Id);
        Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{email});

    }

4.Visualforce方式:代码不是万能的,但是没有代码是万万不能的,遇到恶心的html不好解决的,可以使用visualforce方式搞定,visualforce方式不可以应用到MassEmail中。其中:

1.头标签必须为messaging:emailTemplate;

2.recipientType设置需要引用的是Contact/User/Lead中的哪种,类似email中的setTargetObjectId();

3.relatedToType设置需要引用的其他的object的field,类似email中的setWhatId();

4.使用到User/Contact/Lead字段的地方,使用{!recipient.field_name__c}来代替;

5.使用到其他的object的字段的地方,使用{!relatedTo.field_name__c}来代替;

<messaging:emailTemplate subject="Test Subject Use Visualforce Component" language="{!recipient.Languages__c}" recipientType="Contact" relatedToType="Goods__c">
    <messaging:htmlEmailBody>
        <style type="text/css">
            p {
                border: 3px;
                background: #cccccc;
            }
        </style>
        <div>
            this is a visualforce component email template
        </div>
        <div>
            <p>{!$ObjectType.Goods__c.Fields.GoodsName__c.Label} : {!relatedTo.GoodsName__c}</p>
            <p>{!$ObjectType.Contact.Fields.Name.Label} : {!recipient.Name}</p>
        </div>
    </messaging:htmlEmailBody>
    <messaging:attachment filename="ExportGoods.csv">
        <apex:repeat value="{!relatedTo}" var="goods">
            {!goods.GoodsName__c}
            {!goods.GoodsBrand__c}
        </apex:repeat>
    </messaging:attachment>
</messaging:emailTemplate>

邮件的调用方式和其他的调用方式相同,但是搜索emailtemplate的subject和body会变成空。

    public void sendEmailWithVisualforceComponent() {
        EmailTemplate temp =  [
            SELECT Id, Name, Subject, HtmlValue, Body, BrandTemplateId
            FROM EmailTemplate
            WHERE DeveloperName = 'Test_Email_Template_With_Component'
            LIMIT 1
        ];
        //String subjectFormat = String.format(temp.Subject, new List<String>{'test subject title'});
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        Contact con = [SELECT Id FROM Contact where name = 'york zhang'];
        Goods__c goods = [select id from Goods__c limit 1];
        email.setTargetObjectId(con.Id);
        email.setSaveAsActivity(false);
        email.setWhatId(goods.Id);
        email.setTemplateId(temp.Id);
        Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{email});
    }

使用email template的相关限制可参看:https://help.salesforce.com/articleView?id=merge_fields_email_templates.htm&type=0

总结:本篇主要描述SingleEmailMessaging的使用以及template的用法,篇中有描述错误的地方欢迎指出,不懂得地方欢迎留言。

posted @ 2017-03-24 22:48  zero.zhang  阅读(6202)  评论(14编辑  收藏  举报