0

I have a method to send email with attachment but some weird stuff keeps occuring where some emails + attachment arrived to the accounts that are returned by the query but some didnt receive anything but the custom timestamp gets updated by the DML statement here,

  IF(mails.size() >0){
                Messaging.sendEmail(mails, false);

                /***** updates Account date of last sendout to avoid multiple sendouts ****/
                FOR(Account acc : accounts){
                    acc.LastInvoiceNoticeDate__c = system.today();
                }

                update accounts;

            }

enter image description here which indicates that those accounts were returned by the query.

full code;

public class automatedCommunication{

    public EmailTemplate ExpiringContract;
    public EmailTemplate DueInvoice;
    public EmailTemplate BlockingOutstanding;
    public EmailTemplate BlockingAccount;
    public EmailTemplate DeactivatingAccount;
    public EmailTemplate LostWinBack;

    public OrgWideEmailAddress orgWideMail = [SELECT Id FROM OrgWideEmailAddress];
    public String country = '';

    public Id emailtemplate;
    public String templateDescription;              // The template description will be assigned to the Task Subject of the task
    public String templateSubject;
    public Id invPDFattachmemt{get;set;}
    public Attachment attach{get;set;}
    public EmailTemplate template;
    public List<Invoice__c> linv;

    public String senderName = 'name';
    public String defaultReplyEmailID = 'test@test.com';
    public String defaultReplyEmailPH = 'test@test.com';
    public String defaultReplyEmailMX = 'test@test.com';

    //Declare the SOQL as string as it will be repeated in multiple classes
    public String expiredConQuery ='SELECT Id, Account.AccountCountry__c, AccountId, Account.AccountManager__r.Email, Account.AccountManager__r.isActive, Account.Owner.Email, Account.Owner.isActive, Account.Contractsigneduntil__c, Account.Due_date_of_last_open_invoice__c FROM Contact WHERE Id in: licontact';


    public void setEmailTemplate(String count){

         //Template for ID
        if(count == 'ID'){
        ExpiringContract = [SELECT Id, Name, Description, Subject FROM EmailTemplate WHERE Name =: 'Contract renewal notice ID' LIMIT 1];
        DueInvoice = [SELECT Id, Name, Description, Subject FROM EmailTemplate WHERE Name =: 'Invoice due reminders ID' LIMIT 1];
        BlockingOutstanding = [SELECT Id, Name, Description, Subject FROM EmailTemplate WHERE Name =: 'Invoice overdue ID' LIMIT 1];
        BlockingAccount = [SELECT Id, Name, Description, Subject FROM EmailTemplate WHERE Name =: 'Account has been blocked ID' LIMIT 1];
        DeactivatingAccount = [SELECT Id, Name, Description, Subject FROM EmailTemplate WHERE Name =: 'Account has been deactivated ID' LIMIT 1];
        }

        //Template for MX
        if(count == 'MX'){
        ExpiringContract = [SELECT Id, Name, Description, Subject FROM EmailTemplate WHERE Name =: '9. Contract renewal notice' LIMIT 1];
        DueInvoice = [SELECT Id, Name, Description, Subject FROM EmailTemplate WHERE Name =: '10. Invoice Due Reminder' LIMIT 1];
        BlockingOutstanding = [SELECT Id, Name, Description, Subject FROM EmailTemplate WHERE Name =: '11. Invoice overdue' LIMIT 1];
        BlockingAccount = [SELECT Id, Name, Description, Subject FROM EmailTemplate WHERE Name =: '12. Account has been blocked' LIMIT 1];
        DeactivatingAccount = [SELECT Id, Name, Description, Subject FROM EmailTemplate WHERE Name =: '13. Account has been Deactivated' LIMIT 1];
        }

        //template for PH
        if(count == 'PH'){
        ExpiringContract = [SELECT Id, Name, Description, Subject FROM EmailTemplate WHERE Name =: 'New Renewal Notice' LIMIT 1];
        DueInvoice = [SELECT Id, Name, Description, Subject FROM EmailTemplate WHERE Name =: 'Invoice Due in 2 Weeks' LIMIT 1];
        BlockingOutstanding = [SELECT Id, Name, Description, Subject FROM EmailTemplate WHERE Name =: 'Blocking Outstanding' LIMIT 1];
        BlockingAccount = [SELECT Id, Name, Description, Subject FROM EmailTemplate WHERE Name =: 'Blocking Account' LIMIT 1];
        DeactivatingAccount = [SELECT Id, Name, Description, Subject FROM EmailTemplate WHERE Name =: 'Deactivated Contract' LIMIT 1];
        }

    }

    public Messaging.SingleEmailMessage createEmailMessage(Id templateName, Id emailAddressId, Id targetObjectId, Id whatId, String accountManagerEmail, boolean accountManagerStatus, String accountOwnerEmail, boolean accountOwnerStatus, String country ){

        String ReplyToEmail;

        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

        mail.setTemplateId(templateName);  
        mail.setOrgWideEmailAddressId(emailAddressId);
        mail.setTargetObjectId(targetObjectId); 
        mail.setWhatId(whatId);

        IF(accountManagerEmail <> null && accountManagerStatus){
            ReplyToEmail = accountManagerEmail;
        }
        ELSE IF(accountOwnerEmail <> null && accountOwnerStatus){
            ReplyToEmail = accountOwnerEmail;
        }
        ELSE IF(country == 'ID'){
            ReplyToEmail = defaultReplyEmailID; 
        }
        ELSE IF(country == 'PH'){
            ReplyToEmail = defaultReplyEmailPH; 
        }
        ELSE{
            ReplyToEmail = defaultReplyEmailMX;      
        }
        mail.setReplyTo(ReplyToEmail); 

        return mail;      
}



    public void sendInvoiceReminderLimit(String selectCountry){
        String ReplyToEmail;

        country = selectCountry;
        this.setEmailTemplate(country);

/**** Set Template ****/
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        Set<Id> ids = new Set<Id>();

/**** Set filters and conditions (recipients and criteria -> To:, When?, who?, why?) ****/
        List<Contact> licontact = [SELECT Id FROM Contact
                            WHERE ContactForContracts__c = TRUE
                            AND Email <> ''
                            AND Account.ExcludeFromAutomatedSendouts__c = FALSE               
                            AND Account.Outstanding_Amount__c >:0
                            AND Account.TypeOfCompany__c = 'Agent / Broker'
                            AND (Account.LastInvoiceNoticeDate__c <: system.today() OR Account.LastInvoiceNoticeDate__c =: null)
                            AND 
                              (Account.Due_date_of_last_open_invoice__c =: system.today() + 14
                            OR Account.Due_date_of_last_open_invoice__c =: system.today() + 7
                            OR Account.Due_date_of_last_open_invoice__c =: system.today() - 7
                            OR Account.Due_date_of_last_open_invoice__c =: system.today()
                            OR (Account.Due_date_of_last_open_invoice__c =: system.today() - 14 AND Account.LastInvoiceNoticeDate__c =: system.today() -7 AND Account.Account_Restriction__c !=: '0. Do not block')
                            OR (Account.Due_date_of_last_open_invoice__c =: system.today() - 28 AND Account.LastInvoiceNoticeDate__c =: system.today() - 14 AND Account.Account_Restriction__c !=: '0. Do not block'))
                            AND Account.AccountCountry__c =: country]; 
        system.debug('aaa' + licontact.size());


/**** Start process ****/

        IF(licontact.size() >0){
            /**** Set parameters ****/
            List<Contact> contacts = new List<Contact>();
            contacts = Database.query(expiredConQuery);

            FOR(Contact cont : contacts){
                ids.add(cont.Account.Id);
            }
            List<Account> accounts = [SELECT LastInvoiceNoticeDate__c FROM Account WHERE Id in: ids];

            List<Invoice__c> linv = [SELECT Id, NetAmount__c, Tax__c, TotalAmount__c, ServicePeriodStartDate__c, ServicePeriodEndDate__c, Account__c, Account__r.Due_date_of_last_open_invoice__c
                                     , InvoiceAutoNumber__c, Contract__c, Account__r.Name, Account__r.AccountCountry__c, Account__r.AccountLegalName__c, Account__r.TaxID__c
                                     , Account__r.BillingStreet, Account__r.BillingCity, Account__r.BillingState, Account__r.BillingPostalCode
                                     , Account__r.BillingCountry, Date_sent__c, Date_1st_reminder_sent__c, Date_2nd_reminder_sent__c 
                                    FROM Invoice__c 
                                    WHERE Account__c in: ids];

             Account parent = [SELECT Id FROM Account where Name =:'Trash Account DO NOT DELETE'];

            /**** Create emails ****/

            FOR(Contact cont : contacts){

                    //If statenments for ID
                    if(cont.Account.Due_date_of_last_open_invoice__c == system.today() + 14) {

                        template = DueInvoice;
                    } 

                    if(cont.Account.Due_date_of_last_open_invoice__c == system.today()) {

                        template = DueInvoice; 
                    } 

                    if(cont.Account.Due_date_of_last_open_invoice__c == system.today() + 7 ){

                        template = DueInvoice;
                    }
                    if(cont.Account.Due_date_of_last_open_invoice__c == system.today() - 7 ){

                        template = BlockingOutstanding;
                    }
                    if(cont.Account.Due_date_of_last_open_invoice__c == system.today() - 14 ) {

                         template = BlockingAccount;
                    }
                     if(cont.Account.Due_date_of_last_open_invoice__c == system.today() - 28 ) {

                         template = DeactivatingAccount;
                    }

                    if(template == null){   
                        continue;
                    }

                emailtemplate = template.Id;

                system.debug('template ' + emailtemplate);


                system.debug('**linv**' + linv.size());

                FOR(Invoice__c inv : linv){

                    /// Create the pdf for attachment ///

                    if(inv.Account__c == cont.AccountId && inv.ServicePeriodStartDate__c == inv.Account__r.Due_date_of_last_open_invoice__c){

                        if(country == 'ID' || country == 'PH'){
                            PageReference BillPDF = new PageReference('/apex/InvoicePDF' + inv.Account__r.AccountCountry__c);
                            String pdfname = 'temp';

                            BillPDF.getParameters().put('id', inv.Id);
                            attach = new Attachment();
                            Blob attachbody;
                            try{
                                attachbody = BillPDF.getContentAsPDF();
                            } catch (VisualForceException e) {
                                attachbody = Blob.valueof(pdfname);
                                }

                            attach.Body = attachbody;
                            attach.Name = 'Invoice' + inv.InvoiceAutoNumber__c + '.pdf';
                            attach.IsPrivate = true;
                            attach.ParentId = parent.Id;
                            insert attach;

                            invPDFattachmemt = attach.Id;

                        /// Attach pdf to mail ///

                            Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
                            efa.setFileName(attach.Name);
                            efa.setBody(attach.Body);

                            mail = createEmailMessage(emailtemplate, orgWideMail.Id, cont.Id, inv.Id, cont.Account.AccountManager__r.Email, cont.Account.AccountManager__r.isActive, cont.Account.Owner.Email, cont.Account.Owner.isActive, cont.Account.AccountCountry__c); 
                            mail.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
                        }
                        else{
                            mail = createEmailMessage(emailtemplate, orgWideMail.Id, cont.Id, inv.Id, cont.Account.AccountManager__r.Email, cont.Account.AccountManager__r.isActive, cont.Account.Owner.Email, cont.Account.Owner.isActive, cont.Account.AccountCountry__c); 
                        }

                        mails.add(mail);
                    }
                }
                    emailtemplate = null;
                    template = null;
                    system.debug('emailtemplate after' + emailtemplate);
                    system.debug('This is the run query: ' + Limits.getQueries());

                    if(Integer.valueof(Limits.getQueries()) >= 70){
                        break;
                    }  
            }

            system.debug(mails.size());
            system.debug(mails);

        /**** Send emails ****/
            IF(mails.size() >0){
                Messaging.sendEmail(mails, false);

                /***** updates Account date of last sendout to avoid multiple sendouts ****/
                FOR(Account acc : accounts){
                    acc.LastInvoiceNoticeDate__c = system.today();
                }

                update accounts;

            }
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.