Last active
August 29, 2015 14:23
-
-
Save zaki-yama/fe561acd1e5d8a57900e to your computer and use it in GitHub Desktop.
[Apex]添付ファイルつきメール送信のサンプル
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 添付ファイルつきのメールを送信するサンプル | |
| */ | |
| // メール | |
| Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); | |
| mail.setToAddresses(new List<String> { '[email protected]' }); | |
| mail.setSubject('Mail Subject'); | |
| mail.setPlainTextBody('Mail body'); | |
| /* | |
| * 1. Salesforce のレコードにひもづく添付ファイルを送信する場合 | |
| */ | |
| ID id = [SELECT Id FROM Opportunity WHERE ...]; | |
| List<Attachment> attachments = [SELECT Name, Body FROM Attachment WHERE ParentId = :id]; | |
| // メールの添付ファイルを設定 | |
| List<Messaging.EmailFileAttachment> emailFileAttachements = new List<Messaging.EmailFileAttachment>(); | |
| for (Attachment att : attachments) { | |
| Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment(); | |
| efa.setFileName('attachment.pdf'); | |
| efa.setBody(att.body); // Attachment クラスの body が Blob | |
| efa.setContentType('application/pdf'); // なくてもいい? | |
| efa.setInline(false); | |
| fas.add(efa); | |
| } | |
| mail.setFileAttachments(fas); | |
| /* 1 ここまで */ | |
| /* | |
| * 2. Visualforce を pdf ファイルとして送る場合 | |
| */ | |
| // 添付ファイルにしたい Viaualforce ページは `renderAs="pdf"` 指定されている | |
| PageReference pr = Page.MyVisualforcePage; | |
| // パラメータのセットが必要な場合はこうする | |
| pr.getParameters().put('id', (String) account.Id); | |
| pr.setRedirect(true); | |
| Blob b = pr.getContent(); | |
| Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment(); | |
| efa.setFileName('attachment.pdf'); | |
| efa.setBody(b); | |
| mail.setFileAttachments(new List<Messaging.EmailFileAttachment> { efa }); | |
| /* 2 ここまで */ | |
| Messaging.sendEmail(new List<Messaging.Email> { mail }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment