2012-06-19 116 views
3

我想發送一封電子郵件,其中包含使用亞馬遜SES API的附件(pdf文件)。用附件發送電子郵件使用亞馬遜SES

我正在使用Symfony2,所以我在我的項目中包含了AmazonWebServiceBundle。 我可以發送一個簡單的電子郵件(即沒有附件)很容易地用下面的代碼:

$ses = $this->container->get('aws_ses'); 
$recip = array("ToAddresses"=>array("[email protected]")); 
$message = array("Subject.Data"=>"My Subject","Body.Text.Data"=>"My Mail body"); 
$result = $ses->send_email("[email protected]",$recip, $message); 

不幸的是,與附件的電子郵件,我需要使用sendRawEmail功能,而不是SEND_EMAIL功能。

我無法找到如何使用這個功能,有人可以幫忙嗎?

回答

0

經過多次嘗試,我得出結論,直接從代碼發送電子郵件到亞馬遜SES太痛苦了。

所以我沒有改變代碼中的東西,而是配置了我的後綴服務器。

我遵循此過程:http://docs.amazonwebservices.com/ses/latest/DeveloperGuide/SMTP.MTAs.Postfix.html並使用STARTTLS配置集成。

我必須要求在亞馬遜控制檯中輸入SMTP憑據。

現在工作正常,郵件通過Amazon SES正常發送。

3

是的,使用SES發送帶附件的電子郵件是一件痛苦的事情。也許這會幫助那些仍在爲之苦苦掙扎的其他人。我寫了一個簡單的類來幫助簡化對sendRawEmail的調用。

用法:

$subject_str = "Some Subject"; 
$body_str = "<strong>Some email body</strong>"; 
$attachment_str = file_get_contents("/htdocs/test/sample.pdf"); 

//send the email 
$result = SESUtils::deliver_mail_with_attachment(
    array('[email protected]', '[email protected]'),  
    $subject_str, $body_str, '[email protected]', 
    $attachment_str); 

//now handle the $result if you wish 

類:

<?php 
require 'AWSSDKforPHP/aws.phar'; 
use Aws\Ses\SesClient; 

/** 
* SESUtils is a tool to make it easier to work with Amazon Simple Email Service 
* Features: 
* A client to prepare emails for use with sending attachments or not 
* 
* There is no warranty - use this code at your own risk. 
* @author sbossen 
* http://right-handed-monkey.blogspot.com 
*/ 
class SESUtils { 

    const version = "1.0"; 
    const AWS_KEY = "your_aws_key"; 
    const AWS_SEC = "your_aws_secret"; 
    const AWS_REGION = "us-east-1"; 
    const BOUNCER = "[email protected]"; //if used, this also needs to be a verified email 
    const LINEBR = "\n"; 
    const MAX_ATTACHMENT_NAME_LEN = 60; 

    /** 
    * Usage 
    * $result = SESUtils::deliver_mail_with_attachment(array('[email protected]', '[email protected]'), $subject_str, $body_str, '[email protected]', $attachment_str); 
    * use $result->success to check if it was successful 
    * use $result->message_id to check later with Amazon for further processing 
    * use $result->result_text to look for error text if the task was not successful 
    * 
    * @param type $to - individual address or array of email addresses 
    * @param type $subject - UTF-8 text for the subject line 
    * @param type $body - Text for the email 
    * @param type $from - email address of the sender (Note: must be validated with AWS as a sender) 
    * @return \ResultHelper 
    */ 
    public static function deliver_mail_with_attachment($to, $subject, $body, $from, &$attachment = "", $attachment_name = "doc.pdf", $attachment_type = "Application/pdf", $is_file = false, $encoding = "base64", $file_arr = null) { 
     $result = new ResultHelper(); 
     //get the client ready 
     $client = SesClient::factory(array(
        'key' => self::AWS_KEY, 
        'secret' => self::AWS_SEC, 
        'region' => self::AWS_REGION 
     )); 
     //build the message 
     if (is_array($to)) { 
      $to_str = rtrim(implode(',', $to), ','); 
     } else { 
      $to_str = $to; 
     } 
     $msg = "To: $to_str".self::LINEBR; 
     $msg .="From: $from".self::LINEBR; 
     //in case you have funny characters in the subject 
     $subject = mb_encode_mimeheader($subject, 'UTF-8'); 
     $msg .="Subject: $subject".self::LINEBR; 
     $msg .="MIME-Version: 1.0".self::LINEBR; 
     $msg .="Content-Type: multipart/alternative;".self::LINEBR; 
     $boundary = uniqid("_Part_".time(), true); //random unique string 
     $msg .=" boundary=\"$boundary\"".self::LINEBR; 
     $msg .=self::LINEBR; 
     //now the actual message 
     $msg .="--$boundary".self::LINEBR; 
     //first, the plain text 
     $msg .="Content-Type: text/plain; charset=utf-8".self::LINEBR; 
     $msg .="Content-Transfer-Encoding: 7bit".self::LINEBR; 
     $msg .=self::LINEBR; 
     $msg .=strip_tags($body); 
     $msg .=self::LINEBR; 
     //now, the html text 
     $msg .="--$boundary".self::LINEBR; 
     $msg .="Content-Type: text/html; charset=utf-8".self::LINEBR; 
     $msg .="Content-Transfer-Encoding: 7bit".self::LINEBR; 
     $msg .=self::LINEBR; 
     $msg .=$body; 
     $msg .=self::LINEBR; 
     //add attachments 
     if (!empty($attachment)) { 
      $msg .="--$boundary".self::LINEBR; 
      $msg .="Content-Transfer-Encoding: base64".self::LINEBR; 
      $clean_filename = mb_substr($attachment_name, 0, self::MAX_ATTACHMENT_NAME_LEN); 
      $msg .="Content-Type: $attachment_type; name=$clean_filename;".self::LINEBR; 
      $msg .="Content-Disposition: attachment; filename=$clean_filename;".self::LINEBR; 
      $msg .=self::LINEBR; 
      $msg .=base64_encode($attachment); 
      //only put this mark on the last entry 
      if (!empty($file_arr)) 
       $msg .="==".self::LINEBR; 
      $msg .="--$boundary"; 
     } 
     if (!empty($file_arr) && is_array($file_arr)) { 
      foreach ($file_arr as $file) { 
       $msg .="Content-Transfer-Encoding: base64".self::LINEBR; 
       $clean_filename = mb_substr($attachment_name, 0, self::MAX_ATTACHMENT_NAME_LEN); 
       $msg .="Content-Type: application/octet-stream; name=$clean_filename;".self::LINEBR; 
       $msg .="Content-Disposition: attachment; filename=$clean_filename;".self::LINEBR; 
       $msg .=self::LINEBR; 
       $msg .=base64_encode($attachment); 
       //only put this mark on the last entry 
       if (!empty($file_arr)) 
        $msg .="==".self::LINEBR; 
       $msg .="--$boundary"; 
      } 
     } 
     //close email 
     $msg .="--".self::LINEBR; 

     //now send the email out 
     try { 
      $ses_result = $client->sendRawEmail(array(
       'RawMessage' => array('Data' => base64_encode($msg))), array('Source' => $from, 'Destinations' => $to_str)); 
      if ($ses_result) { 
       $result->message_id = $ses_result->get('MessageId'); 
      } else { 
       $result->success = false; 
       $result->result_text = "Amazon SES did not return a MessageId"; 
      } 
     } catch (Exception $e) { 
      $result->success = false; 
      $result->result_text = $e->getMessage()." - To: $to_str, Sender: $from, Subject: $subject"; 
     } 
     return $result; 
    } 

} 


class ResultHelper { 

    public $success = true; 
    public $result_text = ""; 
    public $message_id = ""; 

} 

?> 

我已經寫了一篇博客文章,解決這一點,也許這將是對你或他人有用:http://righthandedmonkey.com/2013/06/how-to-use-amazon-ses-to-send-email-php.html

+0

非常有用的,謝謝。令人驚訝的是,這個功能不在AWS PHP SDK中。與其他API相比,SES部分非常稀疏。 –

+0

您的使用代碼中有一個錯誤。 PHP中的文件讀取功能是file_get_contents,而不是get_file_contents。容易滑倒。除此之外,這個答案被削減,粘貼,調整我的情況。再次感謝。 –

+0

上面的代碼並不適用於我,但它工作在RightHandedMonkey這裏提到的完整解決方案:http://righthandedmonkey.com/2013/06/how-to-use-amazon-ses-to-send-email- php.html –

0

我管理以下面的方式創建一個原始MIME消息,使用Amazon SES sendRawEmail發送附件(.pdf文件)的電子郵件。這是用於純JavaScript的用法;我們可以確定它會進一步添加其他內容類型。

  1. 使用圖書館像jsPDF & html2Canvas創建PDF文件&保存內容到一個變量&得到基本64數據:

    var pdfOutput = pdf.output(); 
    var myBase64Data = btoa(pdfOutput); 
    
  2. 使用下面的代碼來創建MIME信息。注意,順序是非常重要的其他電子郵件最終會作爲文本電子郵件公開所有基地64個數據:

    var fileName = "Attachment.pdf"; 
    var rawMailBody = "From: [email protected]\nTo: [email protected]\n"; 
    rawMailBody = rawMailBody + "Subject: Test Subject\n"; 
    rawMailBody = rawMailBody + "MIME-Version: 1.0\n"; 
    rawMailBody = rawMailBody + "Content-Type: multipart/mixed; boundary=\"NextPart\"\n\n"; 
    rawMailBody = rawMailBody + "--NextPart\n"; 
    rawMailBody = rawMailBody + "Content-Type: application/octet-stream\n"; 
    rawMailBody = rawMailBody + "Content-Transfer-Encoding: base64\n"; 
    rawMailBody = rawMailBody + "Content-Disposition: attachment; filename=\"" + fileName + "\"\n\n"; 
    rawMailBody = rawMailBody + "Content-ID random2384928347923784letters\n"; 
    rawMailBody = rawMailBody + myBase64Data+"\n\n"; 
    rawMailBody = rawMailBody + "--NextPart\n"; 
    
  3. 調用sendRawEmail:

    var params = { 
         RawMessage: { 
         Data: rawMailBody 
         }, 
         Destinations: [], 
         Source: '[email protected]' 
        }; 
    
    ses.sendRawEmail(params, function(err, data) { 
        if (err) alert("Error: "+err); // an error occurred 
        else  { 
    
        alert("Success: "+data);   // successful response 
        } 
    
    }); 
    
相關問題