찾다
php教程php手册phpmailer发送邮件代码
phpmailer发送邮件代码 May 25, 2016 pm 04:49 PM
phpmailer암호이메일 보내기

本文章收藏了两款利用phpmailer来发送邮件,当前如果你的机器配置好了php自带的邮件发送功能那更好哦,mail()这个那就更方便了。

<?php
function smtp_mail($sendto_email, $subject, $body) {
    global $mailconfig, $_cfg;
    $mail = new phpmailer();
    $mail->issmtp();
    $mail->host = $mailconfig[&#39;smtpservers&#39;]; //smtp servers
    $mail->smtpauth = true; // 启用smtp验证功能
    $mail->username = $mailconfig[&#39;smtpusername&#39;];
    $mail->password = $mailconfig[&#39;smtppassword&#39;];
    $mail->from = $mailconfig[&#39;smtpfrom&#39;];
    $mail->fromname = $_cfg[&#39;site_name&#39;];
    $mail->charset = "gb2312";
    $mail->encoding = "base64";
    $mail->addaddress($sendto_email, ""); //收件人地址,可以替换成任何想要接收邮件的email信箱,格式是addaddress("收件人email","收件人姓名")
    $mail->addreplyto($mailconfig[&#39;addreplyto&#39;], ""); //增加回复标签addreplyto
    $mail->ishtml(true);
    $mail->subject = $subject;
    $mail->body = $body;
    $mail->altbody = "text/html"; //该属性的设置是在邮件正文不支持html的备用显示
    if (!$mail->send()) {
        return false;
        //echo "邮件发送有误";
        //echo "邮件错误信息: " . $mail->errorinfo;
        
    } else {
        return true;
    }
}
?>

方法二

<?php
class email {
    //---设置全局变量
    var $mailto = ""; // 收件人
    var $mailcc = ""; // 抄送
    var $mailbcc = ""; // 秘密抄送
    var $mailfrom = ""; // 发件人
    var $mailsubject = ""; // 主题
    var $mailtext = ""; // 文本格式的信件主体
    var $mailhtml = ""; // html格式的信件主体
    var $mailattachments = ""; // 附件
    /* 函数setto($inaddress) :用于处理邮件的地址 参数 $inaddress
    为包涵一个或多个字串,email地址变量,使用逗号来分割多个邮件地址
    默认返回值为true
    **********************************************************/
    function setto($inaddress) {
        //--用explode()函数根据","对邮件地址进行分割
        $addressarray = explode(",", $inaddress);
        //--通过循环对邮件地址的合法性进行检查
        for ($i = 0; $icheckemail($addressarray[$i]) == false) return false;
    }
    //--所有合法的email地址存入数组中
    $this->mailto = implode($addressarray, ",");
    return true;
}
/**************************************************
函数 setcc($inaddress) 设置抄送人邮件地址  
参数 $inaddress 为包涵一个或多个邮件地址的字串,email地址变量,  
使用逗号来分割多个邮件地址 默认返回值为true  
**************************************************************/
function setcc($inaddress) {
    //--用explode()函数根据","对邮件地址进行分割
    $addressarray = explode(",", $inaddress);
    //--通过循环对邮件地址的合法性进行检查
    for ($i = 0; $icheckemail($addressarray[$i]) == false) return false;
}
//--所有合法的email地址存入数组中
$this->mailcc = implode($addressarray, ",");
return true;
}
/***************************************************
函数setbcc($inaddress) 设置秘密抄送地址 参数 $inaddress 为包涵一个或多  
个邮件地址的字串,email地址变量,使用逗号来分割多个邮件地址 默认返回值为  
true  
******************************************/
function setbcc($inaddress) {
    //--用explode()函数根据","对邮件地址进行分割
    $addressarray = explode(",", $inaddress);
    //--通过循环对邮件地址的合法性进行检查
    for ($i = 0; $i < count($addressarray); $i++) {
        if ($this->checkemail($addressarray[$i]) == false) return false;
    }
    //--所有合法的email地址存入数组中
    $this->mailbcc = implode($addressarray, ",");
    return true;
}
/*****************************************************************
函数setfrom($inaddress):设置发件人地址 参数 $inaddress 为包涵邮件  
地址的字串默认返回值为true  
***************************************/
function setfrom($inaddress) {
    if ($this->checkemail($inaddress)) {
        $this->mailfrom = $inaddress;
        return true;
    }
    return false;
}
/**********************
函数 setsubject($insubject) 用于设置邮件主题参数$insubject为字串,  
默认返回的是true  
*******************************************/
function setsubject($insubject) {
    if (strlen(trim($insubject)) > 0) {
        $this->mailsubject = ereg_replace("n", "", $insubject);
        return true;
    }
    return false;
}
/****************************************************
函数settext($intext) 设置文本格式的邮件主体参数 $intext 为文本内容默  
认返回值为true  
****************************************/
function settext($intext) {
    if (strlen(trim($intext)) > 0) {
        $this->mailtext = $intext;
        return true;
    }
    return false;
}
/**********************************
函数sethtml($inhtml) 设置html格式的邮件主体参数$inhtml为html格式,  
默认返回值为true  
************************************/
function sethtml($inhtml) {
    if (strlen(trim($inhtml)) > 0) {
        $this->mailhtml = $inhtml;
        return true;
    }
    return false;
}
/**********************
函数 setattachments($inattachments) 设置邮件的附件 参数$inattachments  
为一个包涵目录的字串,也可以包涵多个文件用逗号进行分割 默认返回值为true  
*******************************************/
function setattachments($inattachments) {
    if (strlen(trim($inattachments)) > 0) {
        $this->mailattachments = $inattachments;
        return true;
    }
    return false;
}
/*********************************
函数 checkemail($inaddress) :这个函数我们前面已经调用过了,主要就是  
用于检查email地址的合法性  
*****************************************/
function checkemail($inaddress) {
    return (ereg("^[^@ ]+@([a-za-z0-9-]+.)+([a-za-z0-9-]{2}|net|com|gov|mil|org|edu|int)$", $inaddress));
}
/*************************************************
函数loadtemplate($infilelocation,$inhash,$informat) 读取临时文件并且  
替换无用的信息参数$infilelocation用于定位文件的目录  
$inhash 由于存储临时的值 $informat 由于放置邮件主体  
***********************************************************/
function loadtemplate($infilelocation, $inhash, $informat) {
    /* 比如邮件内有如下内容: dear ~!username~,
     your address is ~!useraddress~ */
    //--其中"~!"为起始标志"~"为结束标志
    $templatedelim = "~";
    $templatenamestart = "!";
    //--找出这些地方并把他们替换掉
    $templatelineout = ""; //--打开临时文件
    if ($templatefile = fopen($infilelocation, "r")) {
        while (!feof($templatefile)) {
            $templateline = fgets($templatefile, 1000);
            $templatelinearray = explode($templatedelim, $templateline);
            for ($i = 0; $i < count($templatelinearray); $i++) {
                //--寻找起始位置
                if (strcspn($templatelinearray[$i], $templatenamestart) == 0) {
                    //--替换相应的值
                    $hashname = substr($templatelinearray[$i], 1);
                    //--替换相应的值
                    $templatelinearray[$i] = ereg_replace($hashname, (string)$inhash[$hashname], $hashname);
                }
            }
            //--输出字符数组并叠加
            $templatelineout.= implode($templatelinearray, "");
        } //--关闭文件fclose($templatefile);
        //--设置主体格式(文本或html)
        if (strtoupper($informat) == "text") return ($this->settext($templatelineout));
        else if (strtoupper($informat) == "html") return ($this->sethtml($templatelineout));
    }
    return false;
}
/*****************************************
函数 getrandomboundary($offset) 返回一个随机的边界值  
参数 $offset 为整数 &ndash; 用于多管道的调用 返回一个md5()编码的字串  
****************************************/
function getrandomboundary($offset = 0) {
    //--随机数生成
    srand(time() + $offset);
    //--返回 md5 编码的32位 字符长度的字串
    return ("----" . (md5(rand())));
}
/********************************************
函数: getcontenttype($infilename)用于判断附件的类型  
**********************************************/
function getcontenttype($infilename) {
    //--去除路径
    $infilename = basename($infilename);
    //--去除没有扩展名的文件
    if (strrchr($infilename, ".") == false) {
        return "application/octet-stream";
    }
    //--提区扩展名并进行判断
    $extension = strrchr($infilename, ".");
    switch ($extension) {
        case ".gif":
            return "image/gif";
        case ".gz":
            return "application/x-gzip";
        case ".htm":
            return "text/html";
        case ".html":
            return "text/html";
        case ".jpg":
            return "image/jpeg";
        case ".tar":
            return "application/x-tar";
        case ".txt":
            return "text/plain";
        case ".zip":
            return "application/zip";
        default:
            return "application/octet-stream";
    }
    return "application/octet-stream";
}
/**********************************************
函数formattextheader把文本内容加上text的文件头  
*****************************************************/
function formattextheader() {
    $outtextheader = "";
    $outtextheader.= "content-type: text/plain;  
charset=us-asciin";
    $outtextheader.= "content-transfer-encoding: 7bitnn";
    $outtextheader.= $this->mailtext . "n";
    return $outtextheader;
} /************************************************
函数formathtmlheader()把邮件主体内容加上html的文件头  
******************************************/
function formathtmlheader() {
    $outhtmlheader = "";
    $outhtmlheader.= "content-type: text/html;  
charset=us-asciin";
    $outhtmlheader.= "content-transfer-encoding: 7bitnn";
    $outhtmlheader.= $this->mailhtml . "n";
    return $outhtmlheader;
}
/**********************************
函数 formatattachmentheader($infilelocation) 把邮件中的附件标识出来  
********************************/
function formatattachmentheader($infilelocation) {
    $outattachmentheader = "";
    //--用上面的函数getcontenttype($infilelocation)得出附件类型
    $contenttype = $this->getcontenttype($infilelocation);
    //--如果附件是文本型则用标准的7位编码
    if (ereg("text", $contenttype)) {
        $outattachmentheader.= "content-type: " . $contenttype . ";n";
        $outattachmentheader.= &#39; name="&#39; . basename($infilelocation) . &#39;"&#39; . "n";
        $outattachmentheader.= "content-transfer-encoding: 7bitn";
        $outattachmentheader.= "content-disposition: attachment;n";
        $outattachmentheader.= &#39; filename="&#39; . basename($infilelocation) . &#39;"&#39; . "nn";
        $textfile = fopen($infilelocation, "r");
        while (!feof($textfile)) {
            $outattachmentheader.= fgets($textfile, 1000);
        }
        //--关闭文件 fclose($textfile);
        $outattachmentheader.= "n";
    }
    //--非文本格式则用64位进行编码
    else {
        $outattachmentheader.= "content-type: " . $contenttype . ";n";
        $outattachmentheader.= &#39; name="&#39; . basename($infilelocation) . &#39;"&#39; . "n";
        $outattachmentheader.= "content-transfer-encoding: base64n";
        $outattachmentheader.= "content-disposition: attachment;n";
        $outattachmentheader.= &#39; filename="&#39; . basename($infilelocation) . &#39;"&#39; . "nn";
        //--调用外部命令uuencode进行编码
        exec("uuencode -m $infilelocation nothing_out", $returnarray);
        for ($i = 1; $i < (count($returnarray)); $i++) {
            $outattachmentheader.= $returnarray[$i] . "n";
        }
    }
    return $outattachmentheader;
}
/******************************
函数 send()用于发送邮件,发送成功返回值为true  
************************************/
function send() {
    //--设置邮件头为空
    $mailheader = "";
    //--添加抄送人
    if ($this->mailcc != "") $mailheader.= "cc: " . $this->mailcc . "n";
    //--添加秘密抄送人
    if ($this->mailbcc != "") $mailheader.= "bcc: " . $this->mailbcc . "n";
    //--添加发件人
    if ($this->mailfrom != "") $mailheader.= "from: " . $this->mailfrom . "n";
    //---------------------------邮件格式------------------------------
    //--文本格式
    if ($this->mailtext != "" && $this->mailhtml == "" && $this->mailattachments == "") {
        return mail($this->mailto, $this->mailsubject, $this->mailtext, $mailheader);
    }
    //--html或text格式
    else if ($this->mailtext != "" && $this->mailhtml != "" && $this->mailattachments == "") {
        $bodyboundary = $this->getrandomboundary();
        $textheader = $this->formattextheader();
        $htmlheader = $this->formathtmlheader();
        //--设置 mime-版本
        $mailheader.= "mime-version: 1.0n";
        $mailheader.= "content-type: multipart/alternative;n";
        $mailheader.= &#39; boundary="&#39; . $bodyboundary . &#39;"&#39;;
        $mailheader.= "nnn";
        //--添加邮件主体和边界
        $mailheader.= "--" . $bodyboundary . "n";
        $mailheader.= $textheader;
        $mailheader.= "--" . $bodyboundary . "n";
        //--添加html标签
        $mailheader.= $htmlheader;
        $mailheader.= "n--" . $bodyboundary . "--";
        //--发送邮件
        return mail($this->mailto, $this->mailsubject, "", $mailheader);
    }
    //--文本加html加附件
    else if ($this->mailtext != "" && $this->mailhtml != "" && $this->mailattachments != "") {
        $attachmentboundary = $this->getrandomboundary();
        $mailheader.= "content-type: multipart/mixed;n";
        $mailheader.= &#39; boundary="&#39; . $attachmentboundary . &#39;"&#39; . "nn";
        $mailheader.= "this is a multi-part message in mime format.n";
        $mailheader.= "--" . $attachmentboundary . "n";
        $bodyboundary = $this->getrandomboundary(1);
        $textheader = $this->formattextheader();
        $htmlheader = $this->formathtmlheader();
        $mailheader.= "mime-version: 1.0n";
        $mailheader.= "content-type: multipart/alternative;n";
        $mailheader.= &#39; boundary="&#39; . $bodyboundary . &#39;"&#39;;
        $mailheader.= "nnn";
        $mailheader.= "--" . $bodyboundary . "n";
        $mailheader.= $textheader;
        $mailheader.= "--" . $bodyboundary . "n";
        $mailheader.= $htmlheader;
        $mailheader.= "n--" . $bodyboundary . "--";
        //--获取附件值
        $attachmentarray = explode(",", $this->mailattachments);
        //--根据附件的个数进行循环
        for ($i = 0; $i < count($attachmentarray); $i++) {
            //--分割 $mailheader .= "n--".$attachmentboundary. "n";
            //--附件信息
            $mailheader.= $this->formatattachmentheader($attachmentarray[$i]);
        }
        $mailheader.= "--" . $attachmentboundary . "--";
        return mail($this->mailto, $this->mailsubject, "", $mailheader);
    }
    return false;
}
}
?>

使用方法:

<?php
include "email.class"$mail->setto("a@a.com"); //收件人
$mail->setcc("b@b.com,[url=mailto:c@c.com]c@c.com[/url]"); //抄送
$mail->setcc("d@b.com,[url=mailto:e@c.com]e@c.com[/url]"); //秘密抄送
$mail->setfrom("[url=mailto:f@f.com]f@f.com[/url]"); //发件人
$mail->setsubject("主题"); //主题
$mail->settext("文本格式"); //发送文本格式也可以是变量
$mail->sethtml("html格式"); //发送html格式也可以是变量
$mail->setattachments("c:a.jpg"); //添加附件,需表明路径
$mail->send(); //发送邮件
?>


教程地址:

欢迎转载!但请带上文章地址^^

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
PHP使用PHPMailer发送多人邮件的方法和步骤PHP使用PHPMailer发送多人邮件的方法和步骤May 22, 2023 pm 06:10 PM

在Web应用程序中,往往需要将邮件一次性发送给多个收件人。PHP是一种很流行的Web开发语言,而PHPMailer是一种常见的发送邮件的PHP类库。PHPMailer提供了丰富的接口,使得在PHP应用程序中发送邮件变得更加方便和易于使用。在本篇文章中,我们将介绍如何使用PHPMailer向多个收件人发送邮件的方法和步骤。下载PHPMailer首先需要在官网(

掌握PHP和PHPMAILER:如何实现邮件发送的自动回复功能?掌握PHP和PHPMAILER:如何实现邮件发送的自动回复功能?Jul 22, 2023 am 11:57 AM

掌握PHP和PHPMAILER:如何实现邮件发送的自动回复功能?在现代社会中,电子邮件成为了人们日常沟通的重要方式之一。许多网站或者企业都需要通过邮件与用户进行沟通和交流,并且自动回复邮件变得非常重要。本文将介绍如何使用PHP和PHPMailer库实现邮件发送的自动回复功能。第一步:获取用户的邮件信息首先,我们需要获取用户的邮件信息。在网站或者应用程序中,用

如何使用PHP和PHPMAILER发送带有内嵌图片的HTML邮件?如何使用PHP和PHPMAILER发送带有内嵌图片的HTML邮件?Jul 22, 2023 am 11:29 AM

如何使用PHP和PHPMAILER发送带有内嵌图片的HTML邮件?HTML邮件是一种更加丰富和个性化的邮件形式,可以在邮件中插入图片、链接和样式。而内嵌图片是指在HTML邮件中直接将图片作为邮件的一部分发送,而不是通过附件方式发送。在PHP中,我们可以借助PHPMAILER来发送带有内嵌图片的HTML邮件。PHPMAILER是一个功能强大的PHP邮件发送类库

PHP和PHPMAILER:如何实现邮件发送的防垃圾邮件功能?PHP和PHPMAILER:如何实现邮件发送的防垃圾邮件功能?Jul 22, 2023 am 11:46 AM

PHP和PHPMAILER:如何实现邮件发送的防垃圾邮件功能?引言:在互联网时代,电子邮件已经成为了我们日常生活和工作中不可或缺的一部分。然而,随着电子邮件的普及和使用,垃圾邮件问题日益严重,给用户带来了诸多困扰。为了解决这个问题,本文将介绍如何利用PHP和PHPMailer库实现邮件发送的防垃圾邮件功能。一、了解垃圾邮件垃圾邮件(Spam),指的是那些未经

PHP使用PHPMailer库发送附件邮件的方法和注意事项PHP使用PHPMailer库发送附件邮件的方法和注意事项May 21, 2023 pm 06:12 PM

PHP使用PHPMailer库发送附件邮件的方法和注意事项邮件在现代生活中已经成为了非常重要的一种通信方式。在很多开发项目中,我们需要使用代码自动发送邮件,这时候PHPMailer库就是我们的不二之选。PHPMailer是一个专门用于PHP发送邮件的库。它可以方便地发送邮件,包括HTML格式的邮件和附件。本文将着重介绍PHPMailer库中如何发送带附件的邮

如何在CakePHP中使用PHPMailer?如何在CakePHP中使用PHPMailer?Jun 04, 2023 pm 01:10 PM

CakePHP是一个基于MVC模式的PHP开源框架,旨在为开发者提供高效、可扩展、易于维护的Web应用程序开发环境。其中,邮件功能一直是Web应用程序的重要组成部分之一。为了方便开发者使用邮件功能,在CakePHP中已经封装了PHPMailer类库。PHPMailer是一款常用的邮件发送类库,支持发送HTML邮件、附件、抄送、邮件队列和SMTP验证等功能。本

如何使用PHP和PHPMAILER发送HTML格式的邮件?如何使用PHP和PHPMAILER发送HTML格式的邮件?Jul 22, 2023 am 10:14 AM

如何使用PHP和PHPMailer发送HTML格式的邮件?随着互联网的发展,电子邮件已经成为人们日常沟通的重要工具。在开发网站和应用程序时,我们常常需要使用PHP和PHPMailer来发送邮件。本文将为您介绍如何使用PHP和PHPMailer发送HTML格式的邮件,并提供相应的代码示例。第一步:准备工作在开始之前,您需要确保已经安装了PHP和PHPMaile

如何使用PHP和PHPMAILER实现邮件模板的定制化?如何使用PHP和PHPMAILER实现邮件模板的定制化?Jul 22, 2023 pm 05:01 PM

如何使用PHP和PHPMailer实现邮件模板的定制化?随着电子邮件的普及和广泛应用,定制化邮件模板成为了一种非常重要的需求。通过使用PHP和PHPMailer,我们可以轻松地实现邮件模板的定制化,灵活地应对不同的邮件发送需求。本文将介绍如何使用PHP和PHPMailer来设计和发送定制化邮件模板,并提供相应的代码示例。步骤一:安装和配置PHPMailer首

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구