代码之家  ›  专栏  ›  技术社区  ›  Hamed Ghadirian

SwiftMailer损坏带有动态内容的附件(使用mandrill)

  •  1
  • Hamed Ghadirian  · 技术社区  · 10 年前

    如何从mandrill webhook附加动态内容,并使用Swiftmailer和SMTP(mandrill)发送。

    这是我的代码:

    <?php   
    
    if(!isset($_POST['mandrill_events'])) {
    echo 'A mandrill error occurred: Invalid mandrill_events';
    exit;
    }
    
    // -------------- Receive --------------------------
    $mail = array_pop(json_decode($_POST['mandrill_events']));
    
    
    // ----------------- Send ----------------------------------------
    include_once "swiftmailer-master/lib/swift_required.php";
    
    $subject = $mail->msg->subject . " From " . $mail->msg->from_email;
    $from = array('info@myDomain.ir' =>'myDomain');
    $to = array(
      'myEmail@yahoo.com' => 'Hamed Gh'
    );
    
    $transport = Swift_SmtpTransport::newInstance('smtp.mandrillapp.com', 25,tls);
    $transport->setUsername('username');
    $transport->setPassword('***********');
    
    $swift = Swift_Mailer::newInstance($transport);
    
    $message = new Swift_Message($subject);
    $message->setFrom($from);
    
    //I think there is a problem here!!
    foreach ($mail->msg->attachments as $attachment) {
    $myType = $attachment->type;
    $myName = $attachment->name;
    $myContent = $attachment->content;
    
    $attachment = Swift_Attachment::newInstance()
          ->setFilename($myName)
          ->setContentType($myType)
          ->setBody($myContent)
          ;
    $message->attach($attachment);
    }
    
    $body = $mail->msg->html;
    $message->setBody($body, 'text/html');
    
    $message->setTo($to);
    
    $text = "Mandrill speaks plaintext";
    $message->addPart($text, 'text/plain');
    
    if($recipients = $swift->send($message, $failures) )
    {
     echo 'Message successfully sent!';
    } else {
     echo "There was an error:\n";
     print_r($failures);
    }
    ?>
    

    我仔细搜索并阅读了SwiftMailer文档,但找不到解决问题的方法。所有附件在目的地都会损坏!

    1 回复  |  直到 10 年前
        1
  •  0
  •   Remiii    10 年前

    Mandrill中附加文件的内容默认为Base64编码(请参见Json中的.Base64字段)。

    因此,在SwiftMailer中设置附加内容之前,您需要对内容进行解码。

    $myContent = base64_decode($attachment->content);