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
Neethu uNeethu u 

Pdf attachment getting corrupted in email

I am trying to send file as pdf via email. while opening the pdf in mail it is corrupted.
Below is my code.
ContentVersion doc = new ContentVersion();
string before = 'testing base 64';
Blob beforeblob = Blob.valueOf(before);
doc.Title = 'Attachemnt Test';
doc.PathOnClient = 'test5.pdf';
doc.VersionData = beforeblob;
insert doc;

Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
attach.setContentType('application/pdf');
attach.setFileName('Test.pdf');
attach.setInline(false);
attach.Body = doc.VersionData;

//attach.body = EncodingUtil.base64Decode(jsonStr);

String email = 'abc@gmail.com';
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setUseSignature(false);
mail.setToAddresses(new String[] { email });
mail.setSubject('Document Email Demo');
mail.setHtmlBody('Here is the email you requested: Test.pdf');
mail.setFileAttachments(new Messaging.EmailFileAttachment[] { attach });

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

 
Best Answer chosen by Neethu u
Priyananth RPriyananth R
Hi,

Just try this code,
ContentVersion doc = new ContentVersion();
string before = 'testing base 64';
Blob beforeblob = Blob.topdf(before);
doc.Title = 'Attachemnt Test';
doc.PathOnClient = 'test5.pdf';
doc.VersionData = beforeblob;
insert doc;

Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
attach.setContentType('application/pdf');
attach.setFileName('Test.pdf');
attach.setInline(false);
attach.Body = doc.VersionData;

//attach.body = EncodingUtil.base64Decode(jsonStr);

String email = 'abc@gmail.com';
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setUseSignature(false);
mail.setToAddresses(new String[] { email });
mail.setSubject('Document Email Demo');
mail.setHtmlBody('Here is the email you requested: Test.pdf');
mail.setFileAttachments(new Messaging.EmailFileAttachment[] { attach });

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

I hope this will work.