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

▼魔方 西西 提交于 2019-12-02 11:56:41

问题


I just got PHP's mail function to work properly in my test environment.

I have a PHP app that outputs a number of strings. It would be really nice to convert these strings to attachments (*.TXT -files) in an email, without first storing them on disk and having to read them back. Would this be possible in PHP?


回答1:


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.




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/4279577/php-add-attachments-to-emails-on-the-fly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!