How to attach attachments to mail through apex

In Salesforce, you can attach files to an email using Apex by using the Messaging.SingleEmailMessage class and its setAttachments method. Here's an example of how to do it:

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setSubject('Test Email with Attachment');
mail.setBody('This is a test email with an attachment');
mail.setHtmlBody('<p>This is a test email with an attachment</p>');

// Create a file attachment
Blob fileBlob = Blob.valueOf('Hello World!'); // Replace with your file content
FileAttachment fileAttachment = new FileAttachment();
fileAttachment.setBody(fileBlob);
fileAttachment.setName('example.txt');

// Add the attachment to the email
mail.setAttachments(new List<FileAttachment>{fileAttachment});

// Set the recipient(s)
mail.setToList(new List<String>{'[email protected]'});

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

In this example, we create a SingleEmailMessage object and set its subject, body, and HTML body. We then create a FileAttachment object and set its body to a Blob object containing the file content. We add the attachment to the email using the setAttachments method, which takes a list of FileAttachment objects. Finally, we set the recipient(s) and send the email using the Messaging.sendEmail method.

Note that the FileAttachment object requires a Blob object to store the file content. You can create a Blob object from a file on your local machine using the Blob.valueOf method, or you can retrieve a file from a Salesforce attachment using the Attachment class.

Also, make sure to handle any exceptions that may occur during the email sending process, such as network errors or authentication issues.

Here's an example of how to handle exceptions:

try {
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
} catch (MessagingException e) {
    System.debug('Error sending email: ' + e.getMessage());
}