加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

使用PHP将文件附加到电子邮件

发布时间:2020-12-13 17:43:43 所属栏目:PHP教程 来源:网络整理
导读:我有一个应该将文件附加到外发电子邮件的功能.由于某种原因,它只发送空白文件. 有人可以帮忙吗?我已经验证文件本身是正确上传的,并且位于此功能工作所需的确切位置.仅允许.pdf,.doc和.docx 此外,这是在Windows Server上…(我知道,我知道… YUCK!) 这是功能
我有一个应该将文件附加到外发电子邮件的功能.由于某种原因,它只发送空白文件.

有人可以帮忙吗?我已经验证文件本身是正确上传的,并且位于此功能工作所需的确切位置.仅允许.pdf,.doc和.docx

此外,这是在Windows Server上…(我知道,我知道… YUCK!)

这是功能:

function mail_attachment($filename,$path,$mailto,$from_mail,$from_name,$replyto,$subject,$message) {
    $file = str_replace('/','',$path.$filename);
    $file_size = filesize($file);
    $handle = fopen($file,"rb");
    $contenta = fread($handle,$file_size);
    fclose($handle);
    $content = chunk_split(base64_encode($contenta));
    $uid = md5(uniqid(time()));
    $name = basename($file);
    $header = "From: ".$from_name." <".$from_mail.">rn";
    $header .= "Reply-To: ".$replyto."rn";
    $header .= "MIME-Version: 1.0rn";
    $header .= "Content-Type: multipart/mixed; boundary="".$uid.""rnrn";
    $header .= "This is a multi-part message in MIME format.rn";
    $header .= "--".$uid."rn";
    $header .= "Content-type:text/plain; charset=iso-8859-1rn";
    $header .= "Content-Transfer-Encoding: 7bitrnrn";
    $header .= $message."rnrn";
    $header .= "--".$uid."rn";
    $header .= "Content-Type: application/octet-stream; name="".$filename.""rn"; // use different content types here
    $header .= "Content-Transfer-Encoding: base64rn";
    $header .= "Content-Disposition: attachment; filename="".$filename.""rnrn";
    $header .= $content."rnrn";
    $header .= "--".$uid."--";
    if (mail($mailto,"",$header)) {
        return true; // or use booleans here
    } else {
        return false;
    }
}

以下是使用此代码的代码:

//resume
$errors="";
$dbDir="/candidate-resources/files/temp/";
$baseDir=$_SERVER['DOCUMENT_ROOT'].$dbDir;
$validTypes=array(".doc",".pdf",".docx");
$filesToAdd=array();
$atLeastOne=false;
$valid=false;
$qs="";
if(count($_FILES)>0){
    foreach($_FILES as $k=>$v){
        if($v['size']>0){
            $ext=substr($v['name'],strrpos($v['name'],"."));
            if(!in_array($ext,$validTypes)){
                $errors='Only ".doc",".docx",and ".pdf" files can be uploaded. "'.$ext.'" is not a valid file type.';
            }
        }
    }
}
$requireds=array("name","email","message");
foreach($_POST as $k=>$v){//check for injection and spammers
    if(preg_match("/(%0A|%0D|n+|r+)(content-type:|to:|cc:|bcc:)/i",$v) || strpos($v,"http://")!==false || strpos($v,"www.")!==false){
        $errors="HTML,website addresses,and scripting code are not allowed in any field.  Please check your entries and try again.";
    }
    $post[$k]=strip_tags(trim(htmlentities($v)));
}
unset($_POST);
foreach($requireds as $r){
    if(!strlen(trim($post[$r]))){
        $errors.="<li>".ucwords($r)."</li>";
    }
}
if(strlen(trim($errors))){
    $errors="These fields were left blank.  Please fix and resubmit.<ul>".$errors."</ul>";
}
else{
    if(ereg("([[:alnum:].-]+)(@[[:alnum:].-]+.+)",$post['email'])!=true){
        $errors="<p>You must enter a valid email address.</p>";
    }
    else{
        $filename = '';
        $ext = '';
        // upload the file,then attach it to the email,then delete it
        foreach($_FILES as $k=>$v){
            if($v['size']!=0){
                $atLeastOne=true;
                $ext=substr($v['name'],"."));                
                move_uploaded_file($v['tmp_name'],$baseDir . "/" . $v['name']);
                $filename = $v['name'];
            }
        }
        $to = 'avalid@emailaddress';
        $subject="Contact Form";
        $headers="From: ".$post["name"]." <".$post["email"].">rnReply-To: ".$post["email"]."rn";
        $message=$subject."rn=================================================rnrn";
        foreach($post as $k=>$v) {
            if(strlen(trim($v))){
                $message.=ucwords(str_replace("_"," ",$k)).": {$v}rn";
            }
        }
        if(strlen($filename) > 0) {
            mail_attachment($filename,$baseDir,$to,$post["email"],$post["name"],$message);
            //now delete the temp file
            if (file_exists(str_replace('/',$baseDir.$filename))) { 
                unlink(str_replace('/',$baseDir.$filename)); // delete it here only if it exists
            }
        }else{
            mail($to,$message,$headers);
        }
        $errors="true";
    }
}

请原谅…我刚刚继承了这段代码(即:#1 7岁,#2现在他们希望能够将文件附加到此电子邮件中)

解决方法

开始使用 Swiftmailer( documentation)或 PhpMailer,你的生活会更轻松……

Swiftmailer示例:

require_once 'lib/swift_required.php';
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Wonderful Subject')
    ->setFrom(array('john@doe.com' => 'John Doe'))
    ->setTo(array('receiver@domain.org','other@domain.org' => 'A name'))
    ->setBody('Here is the message itself')
    ->attach(Swift_Attachment::fromPath('my-document.pdf'));
$mailer->send($message);

PhpMailer示例:

$mail             = new PHPMailer(); // defaults to using php "mail()"
$mail->SetFrom('name@yourdomain.com','First Last');
$mail->AddReplyTo("name@yourdomain.com","First Last");
$mail->AddAddress("whoto@otherdomain.com","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!";
}

我更喜欢Swiftmailer,但你选择了你最好的选择;-)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读