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
Joe HayesJoe Hayes 

Send email even with no attachments

Hi Everyone,

I have a class that grabs file attachments and attaches them to an email along with a set document and then sends the email.
I am looking to modify this code so that it will grab attachments if there are any, but if there are no attachments only add the set document and send the email,

I have had a look at this but cannot figure out how to get this, I guess it will be if attachment size is > 1 then do this. If not do that.

Would anyone be able to have a look?
 
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
     List<String> toaddress = new List<String>();
     toaddress.add(string.valueof(cf.Email_to_send_confirmation_to__c));
        mail.settoaddresses(toaddress);
        mail.setReplyTo('trainingbookings@certsure.com');
        mail.setSenderDisplayName('Certsure Training');
        mail.setBccSender(false);
        mail.setUseSignature(false);
        mail.saveAsActivity = false;
        mail.setSubject(subject);
        mail.setHtmlBody(htmlBody);

      //Set email file attachments
        List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
        for (Attachment a : [select Id, Name, Body, BodyLength from Attachment where ParentId = :oppr])
        {

     // Add to attachment file list
        Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
        efa.setFileName(a.Name);
        efa.setBody(a.Body);
        fileAttachments.add(efa);
        }

     // for the T&C's
        Document doc = [select id, name, body, contenttype, developername, type from Document where Name = 'Certsure_Training_Terms_And_Conditions'][0];
        Messaging.Emailfileattachment MyDocefa = new Messaging.Emailfileattachment();
        MyDocefa.setContentType(doc.contentType);
        MyDocefa.setFileName(doc.developerName+'.'+doc.type);
        MyDocefa.setBody(doc.Body);
        fileAttachments.add(MyDocefa);
        mail.setFileAttachments(fileAttachments);

      //Send email
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

Hope that all makes sense,

Thanks
Joe
Swaraj Behera 7Swaraj Behera 7
Hi Joe,Can you try the below code and let me know.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
     List<String> toaddress = new List<String>();
     toaddress.add(string.valueof(cf.Email_to_send_confirmation_to__c));
        mail.settoaddresses(toaddress);
        mail.setReplyTo('trainingbookings@certsure.com');
        mail.setSenderDisplayName('Certsure Training');
        mail.setBccSender(false);
        mail.setUseSignature(false);
        mail.saveAsActivity = false;
        mail.setSubject(subject);
        mail.setHtmlBody(htmlBody);

      //Set email file attachments
        List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
        for (Attachment a : [select Id, Name, Body, BodyLength from Attachment where ParentId = :oppr])
        {

     // Add to attachment file list
        Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
        if(a!=null){
                efa.setFileName(a.Name);
                efa.setBody(a.Body);
                fileAttachments.add(efa);
            }   
        }

     // for the T&C's
        Document doc = [select id, name, body, contenttype, developername, type from Document where Name = 'Certsure_Training_Terms_And_Conditions'][0];
        Messaging.Emailfileattachment MyDocefa = new Messaging.Emailfileattachment();
        MyDocefa.setContentType(doc.contentType);
        MyDocefa.setFileName(doc.developerName+'.'+doc.type);
        MyDocefa.setBody(doc.Body);
        fileAttachments.add(MyDocefa);
        mail.setFileAttachments(fileAttachments);

      //Send email
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

 
Joe HayesJoe Hayes
Hi Swaraj,

Thanks for the reply, I think that should work great :)

I am getting an error further down my class where it copies the attachment ID onto my custom object.
I'm not quite sure where I've gone wrong but I'm getting the error:

"List has no rows for assignment to SObject
Error is in expression '{!emailAtt}' in component <apex:commandButton> in page sendtrainingconfirmation: Class.TrainingConfirmationSend.emailAtt: line 92, column 1"

The following code starts at line 90:
cf.has_confirmation_been_sent__c = true;
        Attachment z = [select Id from Attachment where ParentId = :oppr];
            if(z.id!=null){
                cf.AttachmentId__c = z.id;
            }
        update cf;
     
        return null;

Would you be able to see where the problem lies with this?
If possible id also like to select Id from Attachment where ParentId = :oppr AND Filename ends with ".pdf" - is this possible?

Thanks for your help with this it is very much appreciated.

Kind regards
Joe

 
Swaraj Behera 7Swaraj Behera 7
Hi Joe,
Can you please send me the VF page and the controller.
Thanks
Joe HayesJoe Hayes
Hi Sawaraj,

My Controller is:
public class TrainingConfirmationSend {
    ApexPages.StandardController controller;

 public course_sale__c q
 {get;set;}

 public Id oppr
 {get;set;}

Public course_sale__c cf;

 public TrainingConfirmationSend(ApexPages.StandardController ctrl)
 {oppr = ctrl.getRecord().Id;}

 public void GetCustomFields() {
    cf = [SELECT id, Email_to_send_confirmation_to__c, attachmentid__c, triggercheckbox__c, Send_Confirmation_Automatically__c, has_confirmation_been_sent__c, courses__r.venue_address__c, courses__r.Course_Name__c, courses__r.Duration__c, courses__r.Course_Start_Date__c, courses__r.Start_Time__c, courses__r.Finish_Time__c, courses__r.Tutor2__c FROM Course_Sale__c WHERE id = :oppr];
  }
 public PageReference emailAtt()
 {
    EmailTemplate template = [SELECT Id, Subject, HtmlValue, Body FROM EmailTemplate WHERE Name = 'Training_Confirmation_Email'];

    GetCustomFields();

    String subject = template.Subject;
    subject = subject.replace('{!Courses__c.Course_Name__c}', cf.courses__r.Course_Name__c);

    String htmlBody = template.HtmlValue;
    htmlBody = htmlBody.replace('{!Courses__c.Course_Name__c}', cf.courses__r.Course_Name__c);
    htmlBody = htmlBody.replace('{!Courses__c.Duration__c}', cf.courses__r.Duration__c.format());
    htmlBody = htmlBody.replace('{!Courses__c.Course_Start_Date__c}', cf.courses__r.Course_Start_Date__c.format());
    htmlBody = htmlBody.replace('{!Courses__c.Start_Time__c}', cf.courses__r.Start_Time__c);
    htmlBody = htmlBody.replace('{!User.FirstName}', UserInfo.getFirstName());
    htmlBody = htmlBody.replace('{!Courses__c.Finish_Time__c}', cf.courses__r.finish_time__c);
    htmlBody = htmlBody.replace('{!Courses__c.Venue_Address__c}', cf.courses__r.venue_address__c);
    htmlBody = htmlBody.replace('{!Courses__c.Training_Tutor__c}', cf.courses__r.Tutor2__c);
     
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
     List<String> toaddress = new List<String>();
     toaddress.add(string.valueof(cf.Email_to_send_confirmation_to__c));
        mail.settoaddresses(toaddress);
        mail.setReplyTo('training.bookings@niceic.com');
        mail.setSenderDisplayName('Certsure Training');
        mail.setBccSender(false);
        mail.setUseSignature(false);
        mail.saveAsActivity = false;
        mail.setSubject(subject);
        mail.setHtmlBody(htmlBody);

      //Set email file attachments
        List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
        for (Attachment a : [select Id, Name, Body, BodyLength from Attachment where ParentId = :oppr])
        {

     // Add to attachment file list
        Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
        if(a!=null){
                efa.setFileName(a.Name);
                efa.setBody(a.Body);
                fileAttachments.add(efa);
            }
        }

     // for the T&C's
        Document doc = [select id, name, body, contenttype, developername, type from Document where Name = 'Certsure_Training_Terms_And_Conditions'][0];
        Messaging.Emailfileattachment MyDocefa = new Messaging.Emailfileattachment();
        MyDocefa.setContentType(doc.contentType);
        MyDocefa.setFileName(doc.developerName+'.'+doc.type);
        MyDocefa.setBody(doc.Body);
        fileAttachments.add(MyDocefa);
        mail.setFileAttachments(fileAttachments);

     //Send email
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

     //Log Completed Activity
        GetCustomFields();
        String userId = UserInfo.getUserId();
        Task t=new Task();
        t.Subject = 'Confirmation Sent';
        t.Status = 'Completed';
        t.Priority = 'Normal';
        t.Type = 'Email';
        t.ActivityDate = System.Today();
        t.WhatId = cf.id;
        t.Description = 'Confirmation Successfully Sent to '+cf.Email_to_send_confirmation_to__c;
        t.OwnerId = userid;
        t.Priority = 'Normal';
        insert t;
     
        cf.has_confirmation_been_sent__c = true;
        Attachment z = [select Id from Attachment where ParentId = :oppr];
         if(z!=null){
           cf.AttachmentId__c = z.id;
        }
        update cf;

        return null;
}

}

And My VF Page is very simple:
<apex:page showHeader="false" standardController="Course_Sale__c" extensions="TrainingConfirmationSend">
  <apex:form >
  <div align="center"><br></br><br></br>
            <apex:commandButton value="Send Confirmation" action="{!emailAtt}" onComplete="window.close();"/>
  </div>
  </apex:form>
</apex:page>

 
Swaraj Behera 7Swaraj Behera 7
Hi Joe,can you please try below code.
public class TrainingConfirmationSend {
    ApexPages.StandardController controller;

 public course_sale__c q
 {get;set;}

 public Id oppr
 {get;set;}

Public course_sale__c cf;

 public TrainingConfirmationSend(ApexPages.StandardController ctrl)
 {
    oppr = ctrl.getRecord().Id;}

 public void GetCustomFields() {
    cf = [SELECT id, Email_to_send_confirmation_to__c, attachmentid__c, triggercheckbox__c, Send_Confirmation_Automatically__c, has_confirmation_been_sent__c, courses__r.venue_address__c, courses__r.Course_Name__c, courses__r.Duration__c, courses__r.Course_Start_Date__c, courses__r.Start_Time__c, courses__r.Finish_Time__c, courses__r.Tutor2__c FROM Course_Sale__c WHERE id = :oppr];
  }
 public PageReference emailAtt()
 {
    EmailTemplate template = [SELECT Id, Subject, HtmlValue, Body FROM EmailTemplate WHERE Name = 'Training_Confirmation_Email'];

    GetCustomFields();

    String subject = template.Subject;
    subject = subject.replace('{!Courses__c.Course_Name__c}', cf.courses__r.Course_Name__c);

    String htmlBody = template.HtmlValue;
    htmlBody = htmlBody.replace('{!Courses__c.Course_Name__c}', cf.courses__r.Course_Name__c);
    htmlBody = htmlBody.replace('{!Courses__c.Duration__c}', cf.courses__r.Duration__c.format());
    htmlBody = htmlBody.replace('{!Courses__c.Course_Start_Date__c}', cf.courses__r.Course_Start_Date__c.format());
    htmlBody = htmlBody.replace('{!Courses__c.Start_Time__c}', cf.courses__r.Start_Time__c);
    htmlBody = htmlBody.replace('{!User.FirstName}', UserInfo.getFirstName());
    htmlBody = htmlBody.replace('{!Courses__c.Finish_Time__c}', cf.courses__r.finish_time__c);
    htmlBody = htmlBody.replace('{!Courses__c.Venue_Address__c}', cf.courses__r.venue_address__c);
    htmlBody = htmlBody.replace('{!Courses__c.Training_Tutor__c}', cf.courses__r.Tutor2__c);
     
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
     List<String> toaddress = new List<String>();
     toaddress.add(string.valueof(cf.Email_to_send_confirmation_to__c));
        mail.settoaddresses(toaddress);
        mail.setReplyTo('training.bookings@niceic.com');
        mail.setSenderDisplayName('Certsure Training');
        mail.setBccSender(false);
        mail.setUseSignature(false);
        mail.saveAsActivity = false;
        mail.setSubject(subject);
        mail.setHtmlBody(htmlBody);

      //Set email file attachments
        List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
        for (Attachment a : [select Id, Name, Body, BodyLength from Attachment where ParentId = :oppr])
        {

     // Add to attachment file list
        Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
        if(a!=null){
                efa.setFileName(a.Name);
                efa.setBody(a.Body);
                fileAttachments.add(efa);
            }
        }

     // for the T&C's
        Document doc = [select id, name, body, contenttype, developername, type from Document where Name = 'Certsure_Training_Terms_And_Conditions'][0];
        Messaging.Emailfileattachment MyDocefa = new Messaging.Emailfileattachment();
        MyDocefa.setContentType(doc.contentType);
        MyDocefa.setFileName(doc.developerName+'.'+doc.type);
        MyDocefa.setBody(doc.Body);
        fileAttachments.add(MyDocefa);
        mail.setFileAttachments(fileAttachments);

     //Send email
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

     //Log Completed Activity
        GetCustomFields();
        String userId = UserInfo.getUserId();
        Task t=new Task();
        t.Subject = 'Confirmation Sent';
        t.Status = 'Completed';
        t.Priority = 'Normal';
        t.Type = 'Email';
        t.ActivityDate = System.Today();
        t.WhatId = cf.id;
        t.Description = 'Confirmation Successfully Sent to '+cf.Email_to_send_confirmation_to__c;
        t.OwnerId = userid;
        t.Priority = 'Normal';
        insert t;
     
        cf.has_confirmation_been_sent__c = true;
        if(oppr!=null)
        list<Attachment> listattach = [select Id from Attachment where ParentId = :oppr];
         if(listattach.size()>0){
           cf.AttachmentId__c = listattach.id;
        }
        update cf;

        return null;
}

}

Thanks,
Swaraj
Joe HayesJoe Hayes
Thanks for this Swaraj,

I'm getting a Variable does not exist: alstattach.id error on line 95, but I cannot see why!

Do you know?

Thanks
Joe