风君子博客

  • 首页
  • 业界
  • 前端
  • 运维
  • 建站
  • 软件
  • 生活
  • 后端
  • 创投
  • 运营
  • 程序人生
    • 影视
    • 游戏
    • 句子
    • bootstrap4教程
    • 资源
    • 日期计算器
  • 其他
    • 说说
    • 关于本站
  1. 首页
  2. 后端
  3. 正文

PHP利用网易或腾讯qq邮箱实现在线反馈表单提交后自动发邮件到指定邮箱

2019年6月9日 1268点热度 0人点赞 3条评论

PHP在线发邮件代码

为解决一些主机空间或服务器上不带发邮件sendmail程序
给大家提供一个亲测可用的在线发邮件小程序,可按自己要求修改

2020.12.7 更新代码,添加发件人名称自定义功能。

注意以下三个文件需要放在同一目录内。

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP利用smtp类发送邮件范例</title>
</head>
<body>
<form action="sendmail.php" method="post">
    <p>收件人:<input type="text" name="toemail" /></p>
    <p>标&nbsp;&nbsp;题:<input type="text" name="title" /></p>
    <p>内&nbsp;&nbsp;容:<textarea name="content" cols="50" rows="5"></textarea></p>
    <p><input type="submit" value="发送"  /></p>
</form>
</body>
</html>

sendmail.php

该文件中可以修改使用的邮箱,推荐使用腾讯QQ邮箱,如果邮件内容里有手机号和QQ号等内容,网易邮箱会自动当做垃圾邮件拦截导致无法发送到目标邮箱。

<?php
header("Content-type: text/html; charset=utf-8");
    require_once "smtp.class.php";
    //******************** 配置信息 ********************************
    $smtpserver = "smtp.qq.com";//SMTP服务器
    $smtpserverport =587;//SMTP服务器端口  465/587
    $smtpusermail = "875001151@qq.com";//SMTP服务器的用户邮箱
    $smtpemailto = $_POST['toemail'];//发送给谁
	$smtpfromname = "风君子博客"; //发件人名称
    $smtpuser = "875001151@qq.com";//SMTP服务器的用户帐号,注:部分邮箱只需@前面的用户名
    $smtppass = "";//SMTP服务器的授权码(网易和QQ邮箱均使用授权码,不是账号登录密码)
    $mailtitle = $_POST['title'];//邮件主题
    $mailcontent = "<h1>".$_POST['content']."</h1>";//邮件内容
    $mailtype = "HTML";//邮件格式(HTML/TXT),TXT为文本邮件
    //************************ 配置信息 ****************************
    $smtp = new Smtp($smtpserver,$smtpserverport,true,$smtpuser,$smtppass);//这里面的一个true是表示使用身份验证,否则不使用身份验证.
    $smtp->debug = false;//是否显示发送的调试信息
	//$state = $smtp->sendmail($smtpemailto, $smtpusermail, $mailtitle, $mailcontent, $mailtype);
	//添加发件人名称
    $state = $smtp->sendmail($smtpemailto, $smtpusermail, $smtpfromname, $mailtitle, $mailcontent, $mailtype);

    echo "<div style='width:300px; margin:36px auto;'>";
    if($state==""){
        echo "对不起,邮件发送失败!请检查邮箱填写是否有误。";
        echo "<a href='index.html'>点此返回</a>";
        exit();
    }
    echo "恭喜!邮件发送成功!!";
    echo "<a href='index.html'>点此返回</a>";
    echo "</div>";

?>


 

smtp.class.php

<?php
/**
 * email smtp (support php7)
 *
 * Modified by: fengjunzi.com 2020.12.7
 * UPDATE:
 * 1、change ereg to preg_match;change ereg_replace to preg_replace.
 * 2、change var to public/private.
 *
 *
 */


class Smtp
{
    /* Public Variables */
    public $smtp_port;

    public $time_out;

    public $host_name;

    public $log_file;

    public $relay_host;

    public $debug;

    public $auth;

    public $user;

    public $pass;

    /* Private Variables */
    private $sock;

    /* Constractor */
    function __construct($relay_host = "", $smtp_port = 25,$auth = false,$user,$pass)
    {
        $this->debug = FALSE;

        $this->smtp_port = $smtp_port;

        $this->relay_host = $relay_host;

        $this->time_out = 30; //is used in fsockopen()


        $this->auth = $auth;//auth

        $this->user = $user;

        $this->pass = $pass;


        $this->host_name = "localhost"; //is used in HELO command
        $this->log_file = "";

        $this->sock = FALSE;

    }

    /* Main Function */

    //function sendmail($to, $from, $subject = "", $body = "", $mailtype, $cc = "", $bcc = "", $additional_headers = "")
	//增加自定义发件人名称
	function sendmail($to, $from, $fromname, $subject = "", $body = "", $mailtype, $cc = "", $bcc = "", $additional_headers = "")
    {

        $mail_from = $this->get_address($this->strip_comment($from));

        $body = preg_replace("/(^|(\r\n))(\.)/", "\1.\3", $body);

        $header = "MIME-Version:1.0\r\n";

        if($mailtype=="HTML"){

            $header .= "Content-Type:text/html\r\n";

        }

        $header .= "To: ".$to."\r\n";

        if ($cc != "") {

            $header .= "Cc: ".$cc."\r\n";

        }

        //$header .= "From: $from<".$from.">\r\n";
		
		$header .= "From: $fromname<".$from.">\r\n";

        $header .= "Subject: ".$subject."\r\n";

        $header .= $additional_headers;

        $header .= "Date: ".date("r")."\r\n";

        $header .= "X-Mailer:By Redhat (PHP/".phpversion().")\r\n";

        list($msec, $sec) = explode(" ", microtime());

        $header .= "Message-ID: <".date("YmdHis", $sec).".".($msec*1000000).".".$mail_from.">\r\n";

        $TO = explode(",", $this->strip_comment($to));

        if ($cc != "") {

            $TO = array_merge($TO, explode(",", $this->strip_comment($cc)));

        }

        if ($bcc != "") {

            $TO = array_merge($TO, explode(",", $this->strip_comment($bcc)));

        }

        $sent = TRUE;

        foreach ($TO as $rcpt_to) {

            $rcpt_to = $this->get_address($rcpt_to);

            if (!$this->smtp_sockopen($rcpt_to)) {

                $this->log_write("Error: Cannot send email to ".$rcpt_to."\n");

                $sent = FALSE;

                continue;

            }

            if ($this->smtp_send($this->host_name, $mail_from, $rcpt_to, $header, $body)) {

                $this->log_write("E-mail has been sent to <".$rcpt_to.">\n");

            } else {

                $this->log_write("Error: Cannot send email to <".$rcpt_to.">\n");

                $sent = FALSE;

            }

            fclose($this->sock);

            $this->log_write("Disconnected from remote host\n");

        }

        return $sent;

    }

    /* Private Functions */

    function smtp_send($helo, $from, $to, $header, $body = "")
    {

        if (!$this->smtp_putcmd("HELO", $helo)) {

            return $this->smtp_error("sending HELO command");

        }

        //auth
        if($this->auth){

            if (!$this->smtp_putcmd("AUTH LOGIN", base64_encode($this->user))) {

                return $this->smtp_error("sending HELO command");

            }

            if (!$this->smtp_putcmd("", base64_encode($this->pass))) {

                return $this->smtp_error("sending HELO command");

            }

        }


        if (!$this->smtp_putcmd("MAIL", "FROM:<".$from.">")) {

            return $this->smtp_error("sending MAIL FROM command");

        }

        if (!$this->smtp_putcmd("RCPT", "TO:<".$to.">")) {

            return $this->smtp_error("sending RCPT TO command");

        }

        if (!$this->smtp_putcmd("DATA")) {

            return $this->smtp_error("sending DATA command");

        }

        if (!$this->smtp_message($header, $body)) {

            return $this->smtp_error("sending message");

        }

        if (!$this->smtp_eom()) {

            return $this->smtp_error("sending <CR><LF>.<CR><LF> [EOM]");

        }

        if (!$this->smtp_putcmd("QUIT")) {

            return $this->smtp_error("sending QUIT command");

        }

        return TRUE;

    }

    function smtp_sockopen($address)
    {

        if ($this->relay_host == "") {

            return $this->smtp_sockopen_mx($address);

        } else {

            return $this->smtp_sockopen_relay();

        }

    }

    function smtp_sockopen_relay()
    {

        $this->log_write("Trying to ".$this->relay_host.":".$this->smtp_port."\n");

        $this->sock = @fsockopen($this->relay_host, $this->smtp_port, $errno, $errstr, $this->time_out);

        if (!($this->sock && $this->smtp_ok())) {

            $this->log_write("Error: Cannot connenct to relay host ".$this->relay_host."\n");

            $this->log_write("Error: ".$errstr." (".$errno.")\n");

            return FALSE;

        }

        $this->log_write("Connected to relay host ".$this->relay_host."\n");

        return TRUE;

    }

    function smtp_sockopen_mx($address)
    {

        $domain = preg_replace("/^.+@([^@]+)$/", "\1", $address);

        if (!@getmxrr($domain, $MXHOSTS)) {

            $this->log_write("Error: Cannot resolve MX \"".$domain."\"\n");

            return FALSE;

        }


        foreach ($MXHOSTS as $host) {

            $this->log_write("Trying to ".$host.":".$this->smtp_port."\n");

            $this->sock = @fsockopen($host, $this->smtp_port, $errno, $errstr, $this->time_out);

            if (!($this->sock && $this->smtp_ok())) {

                $this->log_write("Warning: Cannot connect to mx host ".$host."\n");

                $this->log_write("Error: ".$errstr." (".$errno.")\n");

                continue;

            }

            $this->log_write("Connected to mx host ".$host."\n");

            return TRUE;

        }

        $this->log_write("Error: Cannot connect to any mx hosts (".implode(", ", $MXHOSTS).")\n");

        return FALSE;

    }

    function smtp_message($header, $body)
    {

        fputs($this->sock, $header."\r\n".$body);

        $this->smtp_debug("> ".str_replace("\r\n", "\r\n"."> ", $header."\n> ".$body."\n> "));

        return TRUE;

    }

    function smtp_eom()
    {

        fputs($this->sock, "\r\n.\r\n");

        $this->smtp_debug(". [EOM]\n");

        return $this->smtp_ok();

    }

    function smtp_ok()
    {

        $response = str_replace("\r\n", "", fgets($this->sock, 512));

        $this->smtp_debug($response."\n");

        if (!preg_match("/^[23]/", $response)) {

            fputs($this->sock, "QUIT\r\n");

            fgets($this->sock, 512);

            $this->log_write("Error: Remote host returned \"".$response."\"\n");

            return FALSE;

        }

        return TRUE;

    }

    function smtp_putcmd($cmd, $arg = "")
    {

        if ($arg != "") {

            if($cmd=="") $cmd = $arg;

            else $cmd = $cmd." ".$arg;

        }

        fputs($this->sock, $cmd."\r\n");

        $this->smtp_debug("> ".$cmd."\n");

        return $this->smtp_ok();

    }

    function smtp_error($string)
    {

        $this->log_write("Error: Error occurred while ".$string.".\n");

        return FALSE;

    }

    function log_write($message)
    {

        $this->smtp_debug($message);

        if ($this->log_file == "") {

            return TRUE;

        }

        $message = date("M d H:i:s ").get_current_user()."[".getmypid()."]: ".$message;

        if (!@file_exists($this->log_file) || !($fp = @fopen($this->log_file, "a"))) {

            $this->smtp_debug("Warning: Cannot open log file \"".$this->log_file."\"\n");

            return FALSE;

        }

        flock($fp, LOCK_EX);

        fputs($fp, $message);

        fclose($fp);


        return TRUE;

    }


    function strip_comment($address)
    {

        $comment = "/\([^()]*\)/";

        while (preg_match($comment, $address)) {

            $address = preg_replace($comment, "", $address);

        }

        return $address;

    }


    function get_address($address)
    {

        $address = preg_replace("/([ \t\r\n])+/", "", $address);

        $address = preg_replace("/^.*<(.+)>.*$/", "\1", $address);

        return $address;

    }

    function smtp_debug($message)
    {

        if ($this->debug) {

            echo $message;

        }

    }

}

 

本文转自:https://blog.csdn.net/xiaohongIT/article/details/83386947

标签: mail php 在线反馈 表单
最后更新:2020年12月7日

风君子

独自遨游何稽首 揭天掀地慰生平

点赞
< 上一篇
下一篇 >

猜你喜欢

  • JetBrains 详解最新成立的 PHP 基金会,公司每年捐赠 100000 美元

  • 中国银行周末能办卡吗

  • 工商银行星期天可以办卡吗

  • 现金价值表什么意思

  • 中国银行周六日可以办银行卡吗

  • 宝塔面板 ImageMagick无法安装解决办法

  • php版zblog保存主题配置时提示Allowed memory size of 268435456 bytes exhausted (tried to allocate 12288 bytes)解决方法

  • wordpress更新插件出现:cURL error 28: Operation timed out after 10001 milliseconds with 0 out of 0 bytes received

  • ZBlogPHP忘记登录密码后怎么办?使用官方密码找回工具

  • zblog怎样设置伪静态?zblog设置伪静态的方法讲解

  • zblogPHP站点如何添加管理友情链接?

  • 宝塔面板lnmp环境运行php提示Warning: require(): open_basedir restriction in effect解决方法

文章评论

  • 细嗅蔷薇

    不能设置发件人名称,有没有什么办法呢?

    2020年12月6日
    回复
    • 风君子

      @细嗅蔷薇 我已经修改了代码,添加了发件人名称字段,你可以测试一下

      2020年12月7日
      回复
      • 细嗅蔷薇

        @风君子 厉害!

        2020年12月7日
        回复
  • 取消回复

    风君子

    独自遨游何稽首 揭天掀地慰生平

    最新 热点 随机
    最新 热点 随机
    英伟达Q1营收83亿美元同比增46% 净利16.2亿下滑15% 美股周三全线上涨:中概股普涨 滴滴大涨超18% 苹果高管劝阻零售店员工加入工会:这让我们更难改善工作条件 马斯克追加62.5亿美元股权融资,承诺最终收购推特 苹果 Apple Watch 彩虹版回环式运动表带 2022 款实物提前上手,看完再决定买不买 微星 Project ZERO 主板曝光:接口位于背面,隐藏多余线缆 国内第四大运营商来了!中国广电 5G SIM 卡首曝 苹果美国 Apple Store 零售店开始推行 iPhone“点击支付” 期货开仓平仓是什么意思?要收手续费吗 低风险理财产品会亏吗?低风险理财产品的风险在哪里
    抖音IP属地准确吗格力电器 2021 年营收 1878.69 亿元同比增长 11.69%施耐德电气顾俊:5G赋能,制造业智能化转型“加速”苹果将 iPad Air 2 和 iPad Mini 2 加入过时产品名单IDC:2021 年中国网络市场规模达 102.4 亿美元,路由器市场同比下滑 2.6%波导股份第一季度净利润 552.94 万元,同比增长 75.79%我们常用谁言寸草心报得三春晖歌颂母爱,它的作者是快播被吊销执照 旗下投资公司均已注销或吊销雷军:小米智能工厂第二期预计明年年底开始投入生产,可年产 1000 万高端手机三星 Galaxy Z Fold 4 首曝渲染图:后摄类似 S22 Ultra,改进铰链与屏下摄像头
    股票分红到账怎么查 苹果鼓励员工接种新冠疫苗 有副作用可带薪休假 我的世界 自动上升水电梯制作攻略 广州全市大排查已发现阳性11例:10万剂1针剂疫苗已调运抵达 什么叫聚益生金私行 万达首家红旗旗舰店正式落地:王健林亲自剪彩,号称“打造新能源汽车服务生态” 南方电网5G智能电网项目成为GSMA首个网络切片PoC案例 三星正式发布Exynos 880:旗舰级5G平台只需1998元 IPO 文件证实:美国电动汽车创企 Rivian 上半年亏损近 10 亿美元 银行卡回执单是什么
    标签聚合
    科技 借款人 腾讯 IT资讯 贷款 马斯克 芯片 手机 iphone 美国 京东 华为 快科技 小米 谷歌 利率 微软 股票 三星 额度 支付宝 汽车 业界 银行卡 银行 信用卡 利息 苹果 特斯拉 秘籍
    Tags
    酒 胡萝卜 食物 私房菜 有什么好处 水果 能吃 鸡蛋 身体 会胖吗 副作用 吃什么 相克 好处 饮食 作用 土豆食谱 方法 牛肉 豆腐 糖 热量 茄子 好吃 营养 皮肤过敏 区别 菜谱 牛肉食谱 功效 怎么做 营养价值 豆腐食谱 维生素 土豆 热菜 食用方法 常吃 健康 排骨 汤类 高血压 牛奶 糖尿病人 做法 吃法 下饭菜 海鲜 一起吃 排骨食谱
    最近评论
    九九 发布于 3 周前(05月06日) 也可能是 IP2LOCATION 数据
    风君子 发布于 5 个月前(12月20日) 直播这么赚钱的吗?
    wanif 发布于 5 个月前(12月18日) 采用你提供的pe制作u盘后无法识别mac硬盘,如何解决?
    robotunl 发布于 5 个月前(12月18日) 可以用了,感谢
    robotunl 发布于 5 个月前(12月17日) DISM++链接下不了了啊,能再发一个么。 还有怎么制作和博主一样的PE u盘。
    tiantian 发布于 10 个月前(08月08日) 谢谢分享!
    欣姐 发布于 1 年前(02月06日) 很有道理啊
    我在東莞上班睡覺工資一千五六 发布于 1 年前(12月16日) 东莞台商都开始搬迁河源,梅州包括赣州一些地方要么就是内地城市,因为电子厂需要大量人力所以基本上都是中...
    我在東莞上班睡覺工資一千五六 发布于 1 年前(12月16日) 这个怎么有意思了,是不是太真实了 :smile: :smile:
    东莞石碣维信五金制品有限公司睡觉一千五六 发布于 1 年前(12月15日) 台商大陆模式搞习惯了去了印度未必成功 :idea:

    COPYRIGHT © 2021 风君子博客. ALL RIGHTS RESERVED.

    豫ICP备14018241号