I want to send a email with attachment, for that using below code

public Attachment attachment 
            if (attachment == null)
            attachment = new Attachment();
            return attachment;

    public PageReference save() {
        String parentId = System.currentPagereference().getParameters().get('pid');

        attachment.OwnerId = UserInfo.getUserId();
        attachment.ParentId = parentId;
        attachment.IsPrivate = false;
        insert attachment;
        //Start: Send Email with Attachment
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] toAddresses = new String[]{UserInfo.getUserEmail()};

    mail.setHtmlBody('Here is the email you requested: '+attachment.Body);

        //Set email file attachments
            List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();

            // Add to attachment file list
            Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
         Attachment att = new Attachment(name = attachment.name, body = attachment.body, parentid = attachment.ParentId);


            //Send email
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        PageReference page = new PageReference('/' + parentId);
            return page;
        catch (Dmlexception e){
             ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR,'Error: Unable to upload the attachment.'));
            return null;
            attachment = new Attachment(); 


It is not throwing any error but email is not sending, Please help me out guys

  • what email settings do you have in Deliverability for your org? – Oleksandr Berehovskyi Jun 13 '17 at 10:11
  • it is having system emails only, do i need to change? – prasad nagamalli Jun 13 '17 at 10:15
  • Please show your VF code too. For better understanding.. – user4567570 Jun 13 '17 at 10:17
  • <apex:pageBlockSection id="block1" title="Upload a Attachment"> <apexLpageBlockSectionItem> <apex:inputFile value="{!Attachment.body}" filename="{!Attachment.name}" /> </apexLpageBlockSectionItem> <apex:commandButton value="Send" action="{!save}" style="#1D1F03" /> – prasad nagamalli Jun 13 '17 at 10:18
  • Did you check the email log for any issues? – Saroj Bera Jun 13 '17 at 10:39

in order to be able to send single email messages, you need to have Access level All email in Deliverability for your organization

  • I changed the Deliverability to All email, then also same result, not working Alexander... – prasad nagamalli Jun 13 '17 at 10:44

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.