问题
I'm going to give this another try because my last question might have been confusing. I have a simple web form consisting of the following some inputs (for now, pretend i have two inputs, name and file input). I want the user to upload a document (if possible restrict to .doc, .docx, .pdf, if this is not possible to accomplish, let's just restrict to .doc), and i want to restrict the size to under 2MB.
Let me rephrase this. The file to be attached is NOT on the webserver. It will dynamically be uploaded to a temporary folder, send via the mail script, and then deleted.
If this is possible to accomplish, please, I need all the help that I can get.
I've tried Swiftmailer, PHPMailer, PEAR, I can't seem to get them to work. All I need is a simple script to send an attached file, nothing more. No validation necessary, nothing.
Any help would be greatly appreciated.
Thanks a lot, Amit
回答1:
It is possible to do with all 3 libraries you listed (PHPMAiler, PEAR and Swiftmailer).
For PHPMailer you can see a tutorial here:
require_once '../class.phpmailer.php';
$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
try {
$mail->AddReplyTo('name@yourdomain.com', 'First Last');
$mail->AddAddress('whoto@otherdomain.com', 'John Doe');
$mail->SetFrom('name@yourdomain.com', 'First Last');
$mail->AddReplyTo('name@yourdomain.com', 'First Last');
$mail->Subject = 'PHPMailer Test Subject via mail(), advanced';
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML(file_get_contents('contents.html'));
$mail->AddAttachment('images/phpmailer.gif'); // attachment
$mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
$mail->Send();
echo "Message Sent OK<P></P>\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
AddAttachment will take a file from your server.
How to upload a file form an HTML form can be found here. Once your email is sent you can delete (unlink) the file from the server.
The PHP manual can help you to better undersand file uploads.
All you want to do is easy to achieve, but it's longer to explain than do it :) But with all the links I gave you you have everything you need. If you have specific questions let me know.
来源:https://stackoverflow.com/questions/3220815/sending-a-simple-attached-file-via-php-mail-function