带有ATTACHMENT的PHP电子邮件表单(有或没有PHPmailer)

时间:2015-03-04 07:48:43

标签: php forms phpmailer

我正在使用以下PHP代码,该代码从HTML表单中获取值并以HTML格式发送电子邮件。这对我来说很好。

现在我需要添加一个ATTACHMENT字段,该字段将附件与电子邮件一起发送(有或没有将文件存储在服务器上)。有人可以建议如何使用或不使用PHPmailer吗?

谢谢!

<?php

if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['address'])) {
    die('Error: Missing variables');
}

$name=$_POST['name'];
$mobile=$_POST['mobile'];
$position=$_POST['position'];
$email=$_POST['email'];
$message=$_POST['message'];

$ip=$_SERVER['REMOTE_ADDR'];

$to="email@server.com";

$headers = "MIME-Version: 1.0\r\n";  
$headers .= "Content-type: text/plain; charset=utf-8\r\n";  
$headers = 'From: '.$_POST['name'].' <'.$_POST['email'].'>';

    'X-Mailer: PHP/' . phpversion();

$subject='Job Application from '.$name."\n\n\n";
$body.='Name: <b>'.$name."</b><br>\n";
$body.='Mobile No: <b>'.$mobile."</b><br>\n";
$body.='Position: <b>'.$position."</b><br>\n";
$body.='Email: <b>'.$email."</b><br>\n";
$body.='Message: <b>'.$message."</b><br>\n";

$body.='IP address of the submitter: '."\n".$ip."\n";

$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: '.$email."\r\n";

if(mail($to, $subject, $body, $headers)) {
    header("Location: thank-you.html"); 
} else {
    echo "Something has gone wrong! Please try again!"; 
}

?>

2 个答案:

答案 0 :(得分:0)

使用PHPMailer更容易.. 您可以获得文档和教程here。 这是基本邮件和附加文件的代码:

<?php
require_once('../class.phpmailer.php');

$mail             = new PHPMailer(); // defaults to using php "mail()"

$body             = file_get_contents('contents.html');
$body             = eregi_replace("[\]",'',$body);

$mail->AddReplyTo("name@yourdomain.com","First Last");

$mail->SetFrom('name@yourdomain.com', 'First Last');

$mail->AddReplyTo("name@yourdomain.com","First Last");

$address = "whoto@otherdomain.com";
$mail->AddAddress($address, "John Doe");

$mail->Subject    = "PHPMailer Test Subject via mail(), basic";

$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

$mail->MsgHTML($body);

$mail->AddAttachment("images/phpmailer.gif");      // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Message sent!";
}

希望这有帮助。

答案 1 :(得分:-1)

$filePath = 'foldername/attachment.zip';

$file = fopen($filePath,'rb'); 
$data = fread($file,filesize($filePath)); 
fclose($file);
$data = chunk_split(base64_encode($data));

Content-Type: application/zip; name="attachment.zip"  
Content-Transfer-Encoding: base64  
Content-Disposition: attachment 

$data

在此行之前添加此代码&#34; if(mail($ to,$ subject,$ body,$ headers)){&#34;。