Php 在ZF2中发送带有附件的电子邮件

Php 在ZF2中发送带有附件的电子邮件,php,zend-framework2,email-attachments,Php,Zend Framework2,Email Attachments,如何在zf2中使用text/plain、text/html和附件发送电子邮件? 我使用此代码通过smtp发送电子邮件: $files = $this->params()->fromFiles(); $smtp = new \Zend\Mail\Transport\Smtp(); $smtp->setAutoDisconnect(true); $optn = new \Zend\Mail\Transport\SmtpOptions(array( 'host'

如何在zf2中使用text/plain、text/html和附件发送电子邮件? 我使用此代码通过smtp发送电子邮件:

$files = $this->params()->fromFiles();
$smtp = new \Zend\Mail\Transport\Smtp();
$smtp->setAutoDisconnect(true);
$optn = new \Zend\Mail\Transport\SmtpOptions(array(
    'host'              => 'mail.myserver.com',
    'connection_class'  => 'login',
    'connection_config' => array(
        'username' => 'user@myserver.com',
        'password' => 'mypassword',
    ),
));
$smtp->setOptions($optn);


$htmlPart = new \Zend\Mime\Part('<p>some html</p>');
$htmlPart->type = Mime::TYPE_HTML;

$textPart = new \Zend\Mime\Part('some text');
$textPart->type = Mime::TYPE_TEXT;

$i=0;
$attaches = array();
foreach($files as $file){
    if ($file['error'])
        continue;
    $attaches[$i] = new \Zend\Mime\Part(file_get_contents($file['tmp_name']));
    $attaches[$i]->type = $file['type'].'; name="'.$file['name'].'"';
    $attaches[$i]->encoding = 'base64';
    $attaches[$i]->disposition = 'attachment';
    $attaches[$i]->filename = $file['name'];
    $i++;
}

$parts = array();
if (count($attaches)>0) {
    $parts = array_merge(array($textPart,$htmlPart),$attaches);
    $type = Mime::MULTIPART_MIXED;
}
else{
    $parts = array($textPart, $htmlPart);
    $type = Mime::MULTIPART_ALTERNATIVE ;
}
$body = new \Zend\Mime\Message();
$body->setParts($parts);

$message = new \Zend\Mail\Message();
$message->setFrom('user@myserver.com');
$message->addTo('receiver@myserver.com');
$message->setSubject('subject');
$message->setEncoding("UTF-8");
$message->setBody($body);
$message->getHeaders()->get('content-type')->setType($type);

$smtp->send($message);
有什么帮助吗?

从以下位置设置类型:

$attaches[$i]->type = $file['type'].'; name="'.$file['name'].'"';
致:


您还需要确认,如果您正在使用SMTP服务,它们是否允许通过协议进行附加

带有附件的电子邮件

$mail = new Zend\Mail\Message();
// build message...
$mail->createAttachment($someBinaryString);
$mail->createAttachment($myImage,
                        'image/gif',
                        Zend\Mime\Mime::DISPOSITION_INLINE,
                        Zend\Mime\Mime::ENCODING_BASE64);
如果希望对为此附件生成的MIME部件进行更多控制,可以使用createAttachment()的返回值修改其属性。createAttachment()方法返回Zend\Mime\Part对象:

$mail = new Zend\Mail\Message();

$at = $mail->createAttachment($myImage);
$at->type        = 'image/gif';
$at->disposition = Zend\Mime\Mime::DISPOSITION_INLINE;
$at->encoding    = Zend\Mime\Mime::ENCODING_BASE64;
$at->filename    = 'test.gif';

$mail->send();
另一种方法是创建Zend\Mime\Part的实例,并使用addAttachment()添加它:


目前,在ZF2(2.2)中,没有简单的方法将多部分/可选正文(对于不能/不想使用html的客户端,html和文本可选)与附件结合起来。 如果将“multipart/alternative”内容类型标题添加到整个邮件中,则在某些电子邮件客户端中不会显示附件(链接)

解决方案是将邮件分成两部分,正文(文本和html)和附件:

$mail = new Zend\Mail\Message();

$at = new Zend\Mime\Part($myImage);
$at->type        = 'image/gif';
$at->disposition = Zend\Mime\Mime::DISPOSITION_INLINE;
$at->encoding    = Zend\Mime\Mime::ENCODING_BASE64;
$at->filename    = 'test.gif';

$mail->addAttachment($at);

$mail->send();

例如:

$content=new mimessage();
$htmlPart=new MimePart(“对不起,我今天要迟到了!

”; $htmlPart->type='text/html'; $textPart=newmimepart(“对不起,我今天要迟到了!”); $textPart->type='text/plain'; $content->setParts(数组($textPart,$htmlPart)); $contentPart=new MimePart($content->generateMessage()); $contentPart->type='multipart/alternative;'。PHP_EOLboundary=“”。$content->getMime()->boundary()。”; $attachment=newmimepart(fopen('/path/to/test.pdf','r'); $attachment->type='application/pdf'; $attachment->encoding=Mime::encoding_BASE64; $attachment->disposition=Mime::disposition\u附件; $body=new mimessage(); $body->setParts(数组($contentPart,$attachment)); $message=新消息(); $message->setEncoding('utf-8') ->地址('mywife@home.com') ->addFrom('myself@office.com') ->setSubject('将迟到') ->立法会($机构); $transport=新的SmtpTransport(); $options=新的SmtpOptions($transportConfig), )); $transport->setOptions($options); $transport->send($message);
对于上述内容,您需要以下使用声明:

use Zend\Mail\Message;
use Zend\Mail\Transport\Smtp as SmtpTransport;
use Zend\Mail\Transport\SmtpOptions;
use Zend\Mime\Mime;
use Zend\Mime\Part as MimePart;
use Zend\Mime\Message as MimeMessage;

ZF1在Zend\u Mail\u Transport\u Abstract中有一个
\u buildBody()
方法,该方法可以自动执行此操作。

我发现它是一个更好的解决方案,所以我正在编写它

Namespace YourNamesapace;

use Zend\Mail\Message as ZendMessage;
use Zend\Mime\Part as MimePart;
use Zend\Mime\Message as MimeMessage;
use Zend\Mail\Transport\Sendmail;
class Testmail
{
    public static function sendMailWithAttachment($to, $subject, $htmlMsg, $dir, $fileName)
    {
        $fileFullPath = $dir . '/' . $fileName;
        // Render content from template
        $htmlContent = $htmlMsg;
        // Create HTML part
        $htmlPart = new MimePart($htmlContent);
        $htmlPart->type = "text/html";
        // Create plain text part
        $stripTagsFilter = new \Zend\Filter\StripTags();
        $textContent = str_ireplace(array("<br />", "<br>"), "\r\n", $htmlContent);
        $textContent = $stripTagsFilter->filter($textContent);
        $textPart = new MimePart($textContent);
        $textPart->type = "text/plain";

        // Create separate alternative parts object
        $alternatives = new MimeMessage();
        $alternatives->setParts(array($textPart, $htmlPart));
        $alternativesPart = new MimePart($alternatives->generateMessage());
        $alternativesPart->type = "multipart/alternative;\n boundary=\"".$alternatives->getMime()->boundary()."\"";

        $body = new MimeMessage();
        $body->addPart($alternativesPart);


        $attachment = new MimePart( file_get_contents($fileFullPath) );
        $attachment->type = \Zend\Mime\Mime::TYPE_OCTETSTREAM;
        $attachment->filename = basename($fileName);
        $attachment->disposition = \Zend\Mime\Mime::DISPOSITION_ATTACHMENT;
        $attachment->encoding = \Zend\Mime\Mime::ENCODING_BASE64;
        $body->addPart($attachment);
        // Create mail message
        $mailMessage = new ZendMessage();
        $mailMessage->setFrom('noreply@example.com', 'from Name');
        $mailMessage->setTo($to);
        $mailMessage->setSubject($subject);
        $mailMessage->setBody($body);
        $mailMessage->setEncoding("UTF-8");
        $mailMessage->getHeaders()->get('content-type')->setType('multipart/mixed');
        $transport = new Sendmail();
        $transport->send($mailMessage);
    }
}
Namespace-yournamespace;
使用Zend\Mail\Message作为ZendMessage;
使用Zend\Mime\Part作为MimePart;
使用Zend\Mime\Message作为MimeMessage;
使用Zend\Mail\Transport\Sendmail;
类测试邮件
{
公共静态函数sendMailWithAttachment($to、$subject、$htmlMsg、$dir、$fileName)
{
$fileFullPath=$dir.'/'.$fileName;
//从模板呈现内容
$htmlContent=$htmlMsg;
//创建HTML部件
$htmlPart=新的MimePart($htmlContent);
$htmlPart->type=“text/html”;
//创建纯文本部分
$stripTagsFilter=new\Zend\Filter\StripTags();
$textContent=str_ireplace(数组(“
”,“
”),“\r\n”,“$htmlContent”); $textContent=$stripTagsFilter->filter($textContent); $textPart=新的MimePart($textContent); $textPart->type=“text/plain”; //创建单独的替代零件对象 $Alternations=new mimessage(); $alternations->setParts(数组($textPart,$htmlPart)); $alternativesPart=新的MimePart($alternatives->generateMessage()); $alternativesPart->type=“多部分/alternative;\n边界=\”。$alternatives->getMime()->边界(); $body=new mimessage(); $body->addPart($alternativesPart); $attachment=新的MimePart(文件获取内容($fileFullPath)); $attachment->type=\Zend\Mime\Mime::type\u OCTETSTREAM; $attachment->filename=basename($filename); $attachment->disposition=\Zend\Mime\Mime::disposition\u attachment; $attachment->encoding=\Zend\Mime\Mime::encoding\u BASE64; $body->addPart($attachment); //创建邮件消息 $mailMessage=new-ZendMessage(); $mailMessage->setFrom('noreply@example.com“,”源于名称“); $mailMessage->setTo$to; $mailMessage->setSubject($subject); $mailMessage->setBody($body); $mailMessage->setEncoding(“UTF-8”); $mailMessage->getHeaders()->get('content-type')->setType('multipart/mixed'); $transport=new Sendmail(); $transport->send($mailMessage); } }
createAttachment方法不存在。@MohamadMehdiHabibi您需要查看上面的链接。不要无缘无故地留下负面反馈。我不会为这个帖子留下负面反馈。它不是我的:|文档中没有附件。这是文档的固定版本。谢谢。但当我用这个代码向gmail地址发送电子邮件时,gmail会在邮件页面中显示文本/普通类型。是的,我也注意到了这一点。无论如何,首选方案应该是阵列中的最后一个。我已编辑了答案。@t能否请您提供一种发送多个附件的方法?引用链接不起作用,请将其删除。谢谢
$mail = new Zend\Mail\Message();

$at = new Zend\Mime\Part($myImage);
$at->type        = 'image/gif';
$at->disposition = Zend\Mime\Mime::DISPOSITION_INLINE;
$at->encoding    = Zend\Mime\Mime::ENCODING_BASE64;
$at->filename    = 'test.gif';

$mail->addAttachment($at);

$mail->send();
use Zend\Mail\Message;
use Zend\Mail\Transport\Smtp as SmtpTransport;
use Zend\Mail\Transport\SmtpOptions;
use Zend\Mime\Mime;
use Zend\Mime\Part as MimePart;
use Zend\Mime\Message as MimeMessage;
Namespace YourNamesapace;

use Zend\Mail\Message as ZendMessage;
use Zend\Mime\Part as MimePart;
use Zend\Mime\Message as MimeMessage;
use Zend\Mail\Transport\Sendmail;
class Testmail
{
    public static function sendMailWithAttachment($to, $subject, $htmlMsg, $dir, $fileName)
    {
        $fileFullPath = $dir . '/' . $fileName;
        // Render content from template
        $htmlContent = $htmlMsg;
        // Create HTML part
        $htmlPart = new MimePart($htmlContent);
        $htmlPart->type = "text/html";
        // Create plain text part
        $stripTagsFilter = new \Zend\Filter\StripTags();
        $textContent = str_ireplace(array("<br />", "<br>"), "\r\n", $htmlContent);
        $textContent = $stripTagsFilter->filter($textContent);
        $textPart = new MimePart($textContent);
        $textPart->type = "text/plain";

        // Create separate alternative parts object
        $alternatives = new MimeMessage();
        $alternatives->setParts(array($textPart, $htmlPart));
        $alternativesPart = new MimePart($alternatives->generateMessage());
        $alternativesPart->type = "multipart/alternative;\n boundary=\"".$alternatives->getMime()->boundary()."\"";

        $body = new MimeMessage();
        $body->addPart($alternativesPart);


        $attachment = new MimePart( file_get_contents($fileFullPath) );
        $attachment->type = \Zend\Mime\Mime::TYPE_OCTETSTREAM;
        $attachment->filename = basename($fileName);
        $attachment->disposition = \Zend\Mime\Mime::DISPOSITION_ATTACHMENT;
        $attachment->encoding = \Zend\Mime\Mime::ENCODING_BASE64;
        $body->addPart($attachment);
        // Create mail message
        $mailMessage = new ZendMessage();
        $mailMessage->setFrom('noreply@example.com', 'from Name');
        $mailMessage->setTo($to);
        $mailMessage->setSubject($subject);
        $mailMessage->setBody($body);
        $mailMessage->setEncoding("UTF-8");
        $mailMessage->getHeaders()->get('content-type')->setType('multipart/mixed');
        $transport = new Sendmail();
        $transport->send($mailMessage);
    }
}