swiftmailer and email form with attachment - beginner

懵懂的女人 提交于 2019-11-29 12:41:00

问题


As always here is the place where I have learned a lot. And I have now a new things to learn:

I have a html form:

<tr><td width="16%">File attachment</td><td width="2%">:</td><td><input type="file" name="fileatt" /></td></tr>

and a mail.php:

$attachfile=$_POST["fileatt"];

and a correct swiftmailer code to send emails out;

I have googled and I found many examples how to send attachment with a file stored on the website but I would like to do it on the fly. So when you submit the button it would send it to peoples out rather than uploading the file.

// Create the Transport
$transport = Swift_SmtpTransport::newInstance('mail.server.co.uk', 25)
->setUsername('user')
->setPassword('pass')
;

// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);

// Create a message
$message = Swift_Message::newInstance($subject)
  ->setFrom(array('emai@emai.com' => 'name'))

   ->setBody($html, 'text/html')
  ;
// Add alternative parts with addPart()
$message->addPart(strip_tags($html), 'text/plain');

// Send the message
$result = $mailer->send($message);

could anyone help me how to do the on the fly file uploading, please? Thanks in advance!!!


回答1:


There's a simple way to do this, here you go:

$message->attach(
Swift_Attachment::fromPath('/path/to/image.jpg')->setFilename('myfilename.jpg')
);

That's one way SwiftMail can do this, now just the /tmp file, and turn the above into the following:

Assuming: fileatt is the variable for the $_FILE, ['tmp_name'] actually is the tmp file that PHP creates from the form upload.

$message->attach(
Swift_Attachment::fromPath($_FILES['fileatt']['tmp_name'])->setFilename($_FILES['fileatt']['name'])
);

More information on SwiftMail Attachments can be found on this docs page

More information on $_FILES can be found here on w3schools, despite I don't like w3schools, this page is solid.




回答2:


Another way to do this, using only a single variable for path and filename is:

$message->attach(Swift_Attachment::fromPath('full-path-with-attachment-name'));


来源:https://stackoverflow.com/questions/11319878/swiftmailer-and-email-form-with-attachment-beginner

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