本文介绍了通过PHPMailer添加附件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下这段代码的PHPMailer。问题是文件成功上传到服务器,但是邮件中没有发送附件。附件代码似乎是我所知的最好的。请检查代码,让我知道我在哪里出错。



表单

 < form name =contactformmethod =postaction =send1.phpenctype =multipart / form-data> 
< table width =100%border =0>
< tr>
< td id =ta>
< label for =title> Title *< / label>
< / td>
< td id =ta>
< select name =title>
< option value =0>标题< / option>
< option value =1>先生< / option>
< option value =2> Ms.< / option>
< option value =3> Mrs.< / option>
< / select>< / td>< / tr>< tr>< td id =ta>
< label for =first_name>名字*< / label>
< / td>
< td id =ta>
< input type =textname =first_namemaxlength =50size =30required =required>
< / td>
< / tr>
< tr>
< td id =ta>
< label for =last_name>姓氏*< / label>
< / td>
< td id =ta>
< input type =textname =last_namemaxlength =50size =30required =required>
< / td>
< / tr>
< tr>
< td id =ta>
< label for =email>电子邮件地址*< / label>
< / td>
< td id =ta>
< input type =textname =emailmaxlength =80size =30required =required>
< / td>
< / tr>
< tr>
< td id =ta>
< label for =telephone>电话号码*< / label>
< / td>
< td id =ta>
< input type =textname =telephonemaxlength =30size =30required =required>
< / td>
< / tr>
< tr>
< td id =ta>
< label for =comments>细节< / label>
< / td>
< td id =ta>
< textarea name =commentsmaxlength =100000cols =25rows =6>< / textarea>
< / td>
< / tr>
< tr>
< td id =ta>
< label for =file>或上传文件(仅限word,excel或pdf)< / label>
< / td>
< td id =ta>
< input type =filename =file>
< / td>
< / tr>
< tr>
< td colspan =2style =text-align:centerid =ta>
< input type =submitvalue =Submit>
< / td>
< / tr>
< / table>
< / form>

send1.php

 <?php 

require('PHPMailer / class.phpmailer.php');

if(isset($ _ POST ['email'])){

//编辑下面的2行以下
// $ email_to =hidden ;
// $ email_subject =要求投资组合检查。$ first_name。。$ last_name;

$ title = array('Title','Mr.','Ms.','Mrs.');
$ selected_key = $ _POST ['title'];
$ selected_val = $ title [$ _ POST ['title']];

$ first_name = $ _POST ['first_name']; // required
$ last_name = $ _POST ['last_name']; // required
$ email_from = $ _POST ['email']; // required
$ telephone = $ _POST ['phone']; //不需要
$ comments = $ _POST ['comments']; // required

if(($ selected_key == 0))
echo< script> alert('请输入你的标题')< / script>;
函数clean_string($ string){
$ bad = array(content-type,bcc:,to:,cc:,href);
return str_replace($ bad,,$ string);
}
$ email_message =;
$ email_message。=标题:$ selected_val。\\\
;
$ email_message。=名字:.clean_string($ first_name)。\\\
;
$ email_message。=Last Name:.clean_string($ last_name)。\\\
;
$ email_message。=电子邮件:.clean_string($ email_from)。\\\
;
$ email_message。=电话:.clean_string($ telephone)\\\
;
$ email_message。=评论:.clean_string($ comments)。\\\
;

$ allowedExts = array(doc,docx,xls,xlsx,pdf);
$ temp = explode(。,$ _FILES [file] [name]);
$ extension = end($ temp);
if(($ _FILES [file] [type] ==application / pdf)
||($ _FILES [file] [type] ==应用程序/ msword)
||($ _FILES [file] [type] ==application / excel)
||($ _FILES [file] [type ] ==application / vnd.ms-excel)
||($ _FILES [file] [type] ==application / x-excel)
||($ _FILES [file] [type] ==application / x-msexcel)
||($ _FILES [file] [type] ==application / vnd.openxmlformats-officedocument .wordprocessingml.document)
||($ _FILES [file] [type] ==application / vnd.openxmlformats-officedocument.spreadsheetml.sheet))

&& in_array($ extension,$ allowedExts))
{
if($ _FILES [file] [error]> 0)
{
echo < script> alert('Error:。$ _FILES [file] [error]。')< / script>;
}
else
{
$ d ='upload /';
$ de = $ d。基本名($ _ FILES [文件] [名]);
move_uploaded_file($ _ FILES [file] [tmp_name],$ de);
$ fileName = $ _FILES ['file'] ['name'];
$ filePath = $ _FILES ['file'] ['tmp_name'];
//仅当文件是上传时才添加
}
}
else
{
echo< script> alert('无效文件' )< /脚本>中;
}

//创建电子邮件标头
$ headers ='From:'$ email_from。\r\\\

'Reply-To:'。$ email_from。\r\\\

'X-Mailer:PHP /'。 phpversion();
//创建一个新的PHPMailer实例
$ mail = new PHPMailer();
//告诉PHPMailer使用SMTP
$ mail-> IsSMTP();
//启用SMTP调试
// 0 =关闭(供生产使用)
// 1 =客户端消息
// 2 =客户端和服务器消息
$ mail-> SMTPDebug = 0;
//要求HTML友好的调试输出
$ mail-> Debugoutput ='html';
//设置邮件服务器的主机名
$ mail-> Host =hidden;
//设置SMTP端口号 - 可能是25,465或587
$ mail-> Port = 25;
//是否使用SMTP验证
$ mail-> SMTPAuth = true;
//用于SMTP验证的用户名
$ mail-> Username =hidden;
//用于SMTP验证的密码
$ mail-> Password =hidden;
//设置从
$ mail-> SetFrom($ email_from,$ first_name。'。$ last_name)发送消息的人;
//设置另一个回复地址
//$mail->AddReplyTo('[email protected]'''First Last');
//将消息发送到
$ mail-> AddAddress('hidden','hidden');
//设置主题行
$ mail-> Subject =请求配置文件检查;
//从外部文件读取HTML消息正文,将引用的图像转换成嵌入式,将HTML转换为基本的纯文本替换文本
$ mail-> MsgHTML($ email_message);
//用手动创建的纯文本正文替换
$ mail-> AltBody ='这是一个纯文本消息体';
//附加图像文件
// $ mail-> AddAttachment($ file);
$ mail-> AddAttachment($ _ FILES ['file'] ['tmp_name'],$ _FILES ['file'] ['name']);
//发送消息,检查错误
if(!$ mail-> Send()){
echo< script> alert('Mailer Error:。$ mail - > ERRORINFO ')< /脚本> 中。
} else {
echo< script> alert('您的请求已提交,我们会尽快与您联系。')< / script>;
标题('Location:main.php');
}
}
?>

编辑邮件成功发送所有的细节。只是附件不会发送。



编辑2:解决更改 $ mail-> MsgHTML to $ mail-> Body ,它的工作!

解决方案

更改

  $ mail-> MsgHTML(); 

  $ MAIL->机体;来源: 


I have this following piece of code of PHPMailer. The problem is, that the file uploads to the server successfully but the attachment is not sent in the mail. The attachment code seems right to the best of my knowledge. Please review the code and let me know where have I gone wrong.

Form

<form name="contactform" method="post" action="send1.php" enctype="multipart/form-data">
<table width="100%" border="0">
<tr>
 <td id="ta">
 <label for="title">Title *</label>
 </td>
 <td id="ta">
 <select name="title">
 <option value="0">Title</option>
 <option value="1">Mr.</option>
 <option value="2">Ms.</option>
 <option value="3">Mrs.</option>
 </select></td></tr><tr><td id="ta">
  <label for="first_name">First Name *</label>
 </td>
 <td id="ta">
  <input  type="text" name="first_name" maxlength="50" size="30" required="required">
 </td>
</tr>
<tr>
 <td id="ta">
  <label for="last_name">Last Name *</label>
 </td>
 <td  id="ta">
  <input  type="text" name="last_name" maxlength="50" size="30" required="required">
 </td>
</tr>
<tr>
 <td id="ta">
  <label for="email">Email Address *</label>
 </td>
 <td  id="ta">
  <input  type="text" name="email" maxlength="80" size="30" required="required">
 </td>
</tr>
<tr>
 <td id="ta">
  <label for="telephone">Telephone Number *</label>
 </td>
 <td  id="ta">
  <input  type="text" name="telephone" maxlength="30" size="30" required="required">
 </td>
</tr>
<tr>
 <td id="ta">
  <label for="comments">Details</label>
 </td>
 <td  id="ta">
  <textarea  name="comments" maxlength="100000" cols="25" rows="6"></textarea>
 </td>
</tr>
<tr>
<td id="ta">
    <label for="file">Or upload a file (only word, excel or pdf)</label>
</td>
<td  id="ta">
<input type="file" name="file">
</td>
</tr>
<tr>
 <td colspan="2" style="text-align:center" id="ta">
  <input type="submit" value="Submit">
 </td>
</tr>
</table>
</form>

send1.php

<?php

require('PHPMailer/class.phpmailer.php');

if(isset($_POST['email'])) {

    // EDIT THE 2 LINES BELOW AS REQUIRED
    //$email_to = "hidden";
    //$email_subject = "Request for Portfolio check up from ".$first_name." ".$last_name;

    $title = array('Title', 'Mr.', 'Ms.', 'Mrs.');
    $selected_key = $_POST['title'];
    $selected_val = $title[$_POST['title']];

    $first_name = $_POST['first_name']; // required
    $last_name = $_POST['last_name']; // required
    $email_from = $_POST['email']; // required
    $telephone = $_POST['telephone']; // not required
    $comments = $_POST['comments']; // required

  if(($selected_key==0))
    echo "<script> alert('Please enter your title')</script>";
    function clean_string($string) {
      $bad = array("content-type","bcc:","to:","cc:","href");
      return str_replace($bad,"",$string);
    }
     $email_message = "";
    $email_message .="Title: ".$selected_val."\n";
    $email_message .= "First Name: ".clean_string($first_name)."\n";
    $email_message .= "Last Name: ".clean_string($last_name)."\n";
    $email_message .= "Email: ".clean_string($email_from)."\n";
    $email_message .= "Telephone: ".clean_string($telephone)."\n";
    $email_message .= "Comments: ".clean_string($comments)."\n";

    $allowedExts = array("doc", "docx", "xls", "xlsx", "pdf");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "application/pdf")
|| ($_FILES["file"]["type"] == "application/msword")
|| ($_FILES["file"]["type"] == "application/excel")
|| ($_FILES["file"]["type"] == "application/vnd.ms-excel")
|| ($_FILES["file"]["type"] == "application/x-excel")
|| ($_FILES["file"]["type"] == "application/x-msexcel")
|| ($_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
|| ($_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))

&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "<script>alert('Error: " . $_FILES["file"]["error"] ."')</script>";
    }
  else
    {
        $d='upload/';
        $de=$d . basename($_FILES['file']['name']);
    move_uploaded_file($_FILES["file"]["tmp_name"], $de);
$fileName = $_FILES['file']['name'];
    $filePath = $_FILES['file']['tmp_name'];
     //add only if the file is an upload
     }
  }
else
  {
  echo "<script>alert('Invalid file')</script>";
  }

// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
//Create a new PHPMailer instance
$mail = new PHPMailer();
//Tell PHPMailer to use SMTP
$mail->IsSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug  = 0;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host       = "hidden";
//Set the SMTP port number - likely to be 25, 465 or 587
$mail->Port       = 25;
//Whether to use SMTP authentication
$mail->SMTPAuth   = true;
//Username to use for SMTP authentication
$mail->Username   = "hidden";
//Password to use for SMTP authentication
$mail->Password   = "hidden";
//Set who the message is to be sent from
$mail->SetFrom($email_from, $first_name.' '.$last_name);
//Set an alternative reply-to address
//$mail->AddReplyTo('[email protected]','First Last');
//Set who the message is to be sent to
$mail->AddAddress('hidden', 'hidden');
//Set the subject line
$mail->Subject = 'Request for Profile Check up';
//Read an HTML message body from an external file, convert referenced images to embedded, convert HTML into a basic plain-text alternative body
$mail->MsgHTML($email_message);
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
//$mail->AddAttachment($file);
$mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']);
//Send the message, check for errors
if(!$mail->Send()) {
  echo "<script>alert('Mailer Error: " . $mail->ErrorInfo."')</script>";
} else {
  echo "<script>alert('Your request has been submitted. We will contact you soon.')</script>";
  Header('Location: main.php');
}
}
?>

EDIT The mail sends successfully with all the details too. Just that the attachment won't send.

EDIT 2: SOLVED Changed $mail->MsgHTML to $mail->Body and it worked!

解决方案

Change

$mail->MsgHTML();

to

$mail->Body;

Source: here

这篇关于通过PHPMailer添加附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 20:57