Проблемы с SingleEmailMessage и cc - PullRequest
0 голосов
/ 30 мая 2018

У меня есть приложение, которое прекрасно работает, если заполнены все поля назначения (To :, cc: и bcc :), но если одно из них не заполнено, я получаю сообщение об ошибке, в котором указан неверный адрес электронной почты.Я использую поля ввода текста и несколько адресов электронной почты разделяются точкой с запятой (;).Если поле ввода пустое, я не назначаю ничего для этой опции.Есть идеи, почему это может произойти?Какое значение я использую для функций setCcAddress и setBccAddresses, чтобы ничего не показывать.Я пробовал несколько (ноль, пустой список).

См. Код ниже.

Расширение:

public class AffEngpdfExtension 
{
public ID callersId;
private String transferUrl;

public String recipientEmail { get; set; }
public String ccEmail { get; set; }
public String bccEmail { get; set; }
public String subjectEmail { get; set; }
public String bodyEmail { get; set; }
public String docName { get; set; }

// Constructor
public AffEngpdfExtension(ApexPages.StandardController stdController) {
    stdController.addFields(new List<String>{ 'Name', 'User_Email__c', 'Oversight_Email__c', 'Sales_Rep_Email__c' });
    Affiliate_Consulting_Engagement__c affEngage;
    affEngage = (Affiliate_Consulting_Engagement__c)stdController.getRecord();

    callersId = stdController.getRecord().id;
    this.recipientEmail = affEngage.User_Email__c;
    ccEmail = affEngage.Oversight_Email__c + ';' + affEngage.Sales_Rep_Email__c;
    List<Contact> senderEmail = [SELECT Id, Email FROM Contact WHERE pse__Salesforce_User__c=:UserInfo.getUserId() LIMIT 1];
    bccEmail = senderEmail[0].Email;
    subjectEmail = 'Affiliate Consulting Engagement ' + affEngage.Name + ' - ' + affEngage.Engagement_Code__c;
    docName = affEngage.Name + '-' + affEngage.Engagement_Code__c;
}
public String TransferPage { get; set; }
// Action method to transfer to a PDF version of the current page !!!
// MUST set the value of TransferPage as part of this Action call !!!
public PageReference transferTopage() {
    transferUrl = '/apex/' + TransferPage + '?scontrolCaching=1&id=' + callersId;
    PageReference pdfPage = new PageReference(transferUrl);
    System.Debug('transferTopage-transferUrl: ' + transferUrl);
    return pdfPage;
}

// Email content...

public PageReference emailPdf() {

    System.Debug('EmailPDF-TransferPage: ' + TransferPage);
    if(String.isBlank(this.TransferPage)) {
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 
           'Internal Error: missing TransferPage in pdfExtension'));
        return null; // early out
    }
    if(String.isBlank(this.recipientEmail)) {
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 
           'You must enter a Send To email address !'));
        return null; // early out
    }
    if(String.isBlank(this.subjectEmail)) {
        subjectEmail = TransferPage;
    }
    String tempstr = this.bodyEmail;
    tempstr = tempstr.replaceall('[^\\W\\D]*','');
    if (String.isBlank(tempstr)) {
        bodyEmail = 'Document(s) attached for your review.';
    }
    // PageReference reportPage = ApexPages.currentPage();
    transferUrl = '/apex/' + TransferPage + '?scontrolCaching=1&id=' + callersId;
    PageReference pdfPage = new PageReference(transferUrl);
    Blob reportPdf;
    try {
        reportPdf = pdfPage.getContentAsPDF();
    }
    catch (Exception e) {
        reportPdf = Blob.valueOf(e.getMessage());
    }
    // Create email
    Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
    List<String> addresses = new List<String>();
    addresses.clear(); 

    if (String.isBlank(this.recipientEmail)) {
        addresses = this.recipientEmail.split(';');
        message.setToAddresses(addresses);
    } else
    addresses.clear();

    if (String.isBlank(this.ccEmail)) {
        addresses = this.ccEmail.split(';');
        message.setCcAddresses(addresses);
    } else
    addresses.clear();

    if (String.isBlank(this.bccEmail)) {
        addresses = this.bccEmail.split(';');
        message.setBccAddresses(addresses);
    } else
    addresses.clear();

    message.setSubject(subjectEmail);
    message.setHtmlBody(bodyEmail);

    // Attach PDF to email and send
    Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment();
    attachment.setContentType('application/pdf');
    attachment.setFileName(TransferPage + '_' + docName + '.pdf'); 
    attachment.setInline(false);
    attachment.setBody(reportPdf);
    message.setFileAttachments(new Messaging.EmailFileAttachment[]{ attachment });
    Messaging.sendEmail(new Messaging.SingleEmailMessage[]{ message });
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,
       'Email with PDF attachment sent to ' + this.recipientEmail));
    return null;
}
}

VF Страница:

<apex:page sidebar="false" showHeader="false" tabStyle="Account" 
       standardController="Affiliate_Consulting_Engagement__c"
       extensions="AffEngpdfExtension"
       applyHtmlTag="false" applyBodyTag="false" >

<apex:form >
    <apex:pageBlock >
        <apex:pageMessages ></apex:pageMessages>
            <apex:pageBlockSection columns="1" >
                <apex:pageBlockSectionItem dataStyle="text-align:left;">
                    <apex:outputLabel for="recipientEmail" value="To:"/> 
                    <apex:inputText value="{!recipientEmail }" size="100"/>
                </apex:pageBlockSectionItem>
                <apex:pageBlockSectionItem dataStyle="text-align:left;">
                    <apex:outputLabel for="ccEmail" value="cc: "/> 
                    <apex:inputText value="{!ccEmail }" size="100"/>
                </apex:pageBlockSectionItem>
                <apex:pageBlockSectionItem dataStyle="text-align:left;">
                    <apex:outputLabel for="recipientEmail" value="bcc:"/> 
                    <apex:inputText value="{!bccEmail }" size="100"/>
                </apex:pageBlockSectionItem>
                <apex:pageBlockSectionItem dataStyle="text-align:left;">
                    <apex:outputLabel for="subjectEmail" value="Email Subject (Optional)"/> 
                    <apex:inputText value="{!subjectEmail }" size="100" />
                </apex:pageBlockSectionItem>
                <apex:pageBlockSectionItem dataStyle="text-align:left;">
                    <apex:outputLabel for="bodyEmail" value="Email Text (Optional)" /> 
                    <apex:inputTextarea value="{!bodyEmail}" rows="6" cols="20" richText="true" />
                </apex:pageBlockSectionItem>
                <apex:pageBlockSectionItem dataStyle="text-align:left;">
                    <apex:commandLink action="{!emailPdf }" value="Email PDF" styleClass="btn" id="btnEmail">
                        <apex:param name="TransferPage"
                        assignTo="{!TransferPage}"
                        value="AffiliateEngagementPdf" />
                    </apex:commandLink>
                </apex:pageBlockSectionItem>
            </apex:pageBlockSection>
        </apex:pageBlock>   
    </apex:form>

<c:AffEngComponent Engage="{!Affiliate_Consulting_Engagement__c }" />    

</apex:page>

1 Ответ

0 голосов
/ 30 мая 2018

Не обращайте внимания на этот вопрос.Мои условия для проверки адресов электронной почты были задом наперед.Я решил это.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...