PHP: Add attachments to emails “on the fly”?

时光毁灭记忆、已成空白 提交于 2019-12-02 03:20:30

Yes, this is possible. You just need to make your email message a multipart message with the following syntax:

MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=random-boundary

This is the optional preamble of a multipart/mixed message.
--random-boundary
Content-Type: text/plain

This is the main message body.
--random-boundary
Content-Type: text/plain
Content-Disposition: attachment; filename=file.txt

This is the content of the attached file.
--random-boundary--
This is the optional epilogue of a multipart/mixed message.

Each part can then be described like any other message. But you should probably use a library that does this for you.

Now if you’re using PHP’s mail function, the first two line would be the header and the rest would be the contents of that mail message. The boundary should be a random boundary so that the possibility of having that string with -- in front of it being in the contents of one part is very unlikely.

Yes, you can use e.g. PEAR's Mail_Mine class for it.

bool addAttachment ( string $file , string $c_type = 'application/octet-stream' , string $name = '' , boolean $isfile = true , string $encoding = 'base64' ) is the method you want to use, with $file containing your strings and $isfile being false.

And you can Use Zend_Mail Classes for much easier code the file name would be "smapleFilename" and its the last parameter in createAttachment function but don't foget to setup your transport before that sample :

    $mail = new Zend_Mail();
        $mail->setBodyText("body")
             ->createAttachment("your wanted text " ,  Zend_Mime::TYPE_TEXT,               
                                 Zend_Mime::DISPOSITION_ATTACHMENT , Zend_Mime::ENCODING_BASE64, "smapleFilename.txt");
        $mail->setFrom('test@222222.com', 'Server');
        $mail->addTo('test@hotmail.com');
        $mail->setSubject("subject");
        $mail->send();

in Zend framework project you would do like this :

resources.mail.transport.type = smtp
resources.mail.transport.host = "mail.111111.com"
resources.mail.transport.auth = login
resources.mail.transport.username = test@111111.com
resources.mail.transport.password = test
;resources.mail.transport.ssl = tls
resources.mail.transport.port = 2525
resources.mail.transport.register = true ; True by default
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!