Heim  >  Artikel  >  Backend-Entwicklung  >  Beispielcode, wie PHP Python aufruft, um schnell E-Mails mit hoher Parallelität zu senden

Beispielcode, wie PHP Python aufruft, um schnell E-Mails mit hoher Parallelität zu senden

黄舟
黄舟Original
2017-07-17 15:33:591843Durchsuche

1 Einführung

Beim Senden von E-Mails in PHP kapseln Sie normalerweise eine PHP-SMTP-E-Mail-Klasse zum Senden von E-Mails. Allerdings ist die zugrunde liegende Socket-Programmierung von PHP im Vergleich zu Python sehr ineffizient. CleverCode hat außerdem einen in Python geschriebenen Crawler zum Crawlen von Webseiten und einen in PHP geschriebenen Crawler zum Crawlen von Webseiten geschrieben. Ich habe festgestellt, dass PHPs Curl zwar zum Crawlen von Webseiten verwendet wird, es jedoch zu Zeitüberschreitungen, gleichzeitigem Crawlen durch mehrere Threads usw. kommt. Ich muss sagen, dass Python bei der Netzwerkprogrammierung viel effizienter ist als PHP.

Wenn PHP E-Mails sendet, weist die selbst geschriebene SMTP-Klasse eine geringe Sendeeffizienz und -geschwindigkeit auf. Insbesondere beim gleichzeitigen Versenden einer großen Anzahl von E-Mails mit angehängten Berichten. Die Effizienz von PHP ist sehr gering. Es wird empfohlen, PHP zum Aufrufen von Python zum Senden von E-Mails zu verwenden.

2 Programm

2.1 Python-Programm

Das PHP-Programm und die Python-Datei müssen in derselben Kodierung vorliegen. Wenn es sich bei allen um GBK-Nummern handelt oder sie gleichzeitig in UTF-8 codiert sind, werden sonst leicht verstümmelte Zeichen angezeigt. Python verwendet hauptsächlich das E-Mail-Modul zum Versenden von E-Mails. Die Python- und PHP-Dateien hier sind alle GBK-codiert, und der Header-Inhalt und der Textinhalt der gesendeten E-Mail sind ebenfalls GBK-codiert.

#!/usr/bin/python
# -*- coding:gbk -*- 
"""
   邮件发送类
"""
# mail.py
#
# Copyright (c) 2014 by http://blog.csdn.net/CleverCode
#
# modification history:
# --------------------
# 2014/8/15, by CleverCode, Create

import threading
import time
import random
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import Utils, Encoders
import mimetypes
import sys
import smtplib
import socket
import getopt
import os

class SendMail:
    def init(self,smtpServer,username,password):
        """
        smtpServer:smtp服务器,        
        username:登录名,
        password:登录密码
        """
        self.smtpServer = smtpServer        
        self.username = username
        self.password = password
    
    def genMsgInfo(self,fromAddress,toAddress,subject,content,fileList,\
            subtype = 'plain',charset = 'gb2312'):
        """
        组合消息发送包
        fromAddress:发件人,
        toAddress:收件人,
        subject:标题,
        content:正文,
        fileList:附件,
        subtype:plain或者html
        charset:编码
        """
        msg = MIMEMultipart()
        msg['From'] = fromAddress
        msg['To'] = toAddress  
        msg['Date'] = Utils.formatdate(localtime=1)
        msg['Message-ID'] = Utils.make_msgid()
        
        #标题
        if subject:
            msg['Subject'] = subject
        
        #内容        
        if content:
            body = MIMEText(content,subtype,charset)
            msg.attach(body)
        
        #附件
        if fileList:
            listArr = fileList.split(',')
            for item in listArr:
                
                #文件是否存在
                if os.path.isfile(item) == False:
                    continue
                    
                att = MIMEText(open(item).read(), 'base64', 'gb2312')
                att["Content-Type"] = 'application/octet-stream'
                #这里的filename邮件中显示什么名字
                filename = os.path.basename(item) 
                att["Content-Disposition"] = 'attachment; filename=' + filename
                msg.attach(att)
        
        return msg.as_string()                
                                                  
    def send(self,fromAddress,toAddress,subject = None,content = None,fileList = None,\
            subtype = 'plain',charset = 'gb2312'):
        """
        邮件发送函数
        fromAddress:发件人,
        toAddress:收件人,
        subject:标题
        content:正文
        fileList:附件列表
        subtype:plain或者html
        charset:编码
        """
        try:
            server = smtplib.SMTP(self.smtpServer)
            
            #登录
            try:
                server.login(self.username,self.password)
            except smtplib.SMTPException,e:
                return "ERROR:Authentication failed:",e
                            
            #发送邮件
            server.sendmail(fromAddress,toAddress.split(',') \
                ,self.genMsgInfo(fromAddress,toAddress,subject,content,fileList,subtype,charset))
            
            #退出
            server.quit()
        except (socket.gaierror,socket.error,socket.herror,smtplib.SMTPException),e:
            return "ERROR:Your mail send failed!",e
           
        return 'OK'


def usage():
    """
    使用帮助
    """
    print """Useage:%s [-h] -s <smtpServer> -u <username> -p <password> -f <fromAddress> -t <toAddress>  [-S <subject> -c
        <content> -F <fileList>]
        Mandatory arguments to long options are mandatory for short options too.
            -s, --smtpServer=  smpt.xxx.com.
            -u, --username=   Login SMTP server username.
            -p, --password=   Login SMTP server password.
            -f, --fromAddress=   Sets the name of the "from" person (i.e., the envelope sender of the mail).
            -t, --toAddress=   Addressee&#39;s address. -t "test@test.com,test1@test.com".          
            -S, --subject=  Mail subject.
            -c, --content=   Mail message.-c "content, ......."
            -F, --fileList=   Attachment file name.            
            -h, --help   Help documen.    
       """ %sys.argv[0]
        
def start():
    """
    
    """
    try:
        options,args = getopt.getopt(sys.argv[1:],"hs:u:p:f:t:S:c:F:","--help --smtpServer= --username= --password= --fromAddress= --toAddress= --subject= --content= --fileList=",)
    except getopt.GetoptError:
        usage()
        sys.exit(2)
        return
    
    smtpServer = None
    username = None
    password = None
               
    fromAddress = None    
    toAddress = None    
    subject = None
    content = None
    fileList = None
    
    #获取参数   
    for name,value in options:
        if name in ("-h","--help"):
            usage()
            return
        
        if name in ("-s","--smtpServer"):
            smtpServer = value
        
        if name in ("-u","--username"):
            username = value
        
        if name in ("-p","--password"):
            password = value
        
        if name in ("-f","--fromAddress"):
            fromAddress = value
        
        if name in ("-t","--toAddress"):
            toAddress = value
        
        if name in ("-S","--subject"):
            subject = value
        
        if name in ("-c","--content"):
            content = value
        
        if name in ("-F","--fileList"):
            fileList = value
    
    if smtpServer == None or username == None or password == None:
        print &#39;smtpServer or username or password can not be empty!&#39;
        sys.exit(3)
           
    mail = SendMail(smtpServer,username,password)
    
    ret = mail.send(fromAddress,toAddress,subject,content,fileList)
    if ret != &#39;OK&#39;:
        print ret
        sys.exit(4)
    
    print &#39;OK&#39;
    
    return &#39;OK&#39;    
     
if name == &#39;main&#39;:
    
    start()

2.2 Hilfe zur Verwendung des Python-Programms

Geben Sie den folgenden Befehl ein, um die Verwendungshilfe dieses Programms auszugeben

# python mail.py --help


2.3 PHP-Programm

Dieses Programm ist hauptsächlich ein PHP-Spleißbefehl String, der ein Python-Programm aufruft. Hinweis: Um E-Mails mit dem Programm zu versenden, müssen Sie zum E-Mail-Dienstanbieter gehen und die STMP-Dienstfunktion aktivieren. In QQ müssen Sie beispielsweise die SMTP-Funktion aktivieren, bevor Sie das Programm zum Versenden von E-Mails verwenden können. Öffnen Sie es wie unten gezeigt.


Das PHP-Aufrufprogramm lautet wie folgt:

<?php

/**
 * SendMail.php
 * 
 * 发送邮件类
 *
 * Copyright (c) 2015 by http://blog.csdn.net/CleverCode
 *
 * modification history:
 * --------------------
 * 2015/5/18, by CleverCode, Create
 *
 */
class SendMail{

    /**
     * 发送邮件方法
     *
     * @param string $fromAddress 发件人,&#39;clevercode@qq.com&#39; 或者修改发件人名 &#39;CleverCode<clevercode@qq.com>&#39;
     * @param string $toAddress 收件人,多个收件人逗号分隔,&#39;test1@qq.com,test2@qq.com,test3@qq.com....&#39;, 或者 &#39;test1<test1@qq.com>,test2<test2@qq.com>,....&#39;
     * @param string $subject 标题
     * @param string $content 正文
     * @param string $fileList 附件,附件必须是绝对路径,多个附件逗号分隔。&#39;/data/test1.txt,/data/test2.tar.gz,...&#39;
     * @return string 成功返回&#39;OK&#39;,失败返回错误信息
     */
    public static function send($fromAddress, $toAddress, $subject = NULL, $content = NULL, $fileList = NULL){
        if (strlen($fromAddress) < 1 || strlen($toAddress) < 1) {
            return &#39;$fromAddress or $toAddress can not be empty!&#39;;
        }
        // smtp服务器
        $smtpServer = &#39;smtp.qq.com&#39;;
        // 登录用户
        $username = &#39;clevercode@qq.com&#39;;
        // 登录密码
        $password = &#39;123456&#39;;
        
        // 拼接命令字符串,实际是调用了/home/CleverCode/mail.py
        $cmd = "LANG=C && /usr/bin/python /home/CleverCode/mail.py";
        $cmd .= " -s &#39;$smtpServer&#39;";
        $cmd .= " -u &#39;$username&#39;";
        $cmd .= " -p &#39;$password&#39;";
        
        $cmd .= " -f &#39;$fromAddress&#39;";
        $cmd .= " -t &#39;$toAddress&#39;";
        
        if (isset($subject) && $subject != NULL) {
            $cmd .= " -S &#39;$subject&#39;";
        }
        
        if (isset($content) && $content != NULL) {
            $cmd .= " -c &#39;$content&#39;";
        }
        
        if (isset($fileList) && $fileList != NULL) {
            $cmd .= " -F &#39;$fileList&#39;";
        }
        
        // 执行命令
        exec($cmd, $out, $status);
        if ($status == 0) {
            return &#39;OK&#39;;
        } else {
            return "Error,Send Mail,$fromAddress,$toAddress,$subject,$content,$fileList ";
        }
        return &#39;OK&#39;;
    }
}

2.3 Anwendungsbeispiel

Excel in einen Anhang komprimieren und senden eine E-Mail.

<?php

/**
 * test.php
 *
 * 压缩excel成附件,发送邮件
 *
 * Copyright (c) 2015 http://blog.csdn.net/CleverCode
 *
 * modification history:
 * --------------------
 * 2015/5/14, by CleverCode, Create
 *
 */
include_once (&#39;SendMail.php&#39;);

/*
 * 客户端类
 * 让客户端和业务逻辑尽可能的分离,降低页面逻辑和业务逻辑算法的耦合,
 * 使业务逻辑的算法更具有可移植性
 */
class Client{

    public function main(){
        
        // 发送者
        $fromAddress = &#39;CleverCode<clevercode@qq.com>&#39;;
        
        // 接收者
        $toAddress = &#39;all@qq.com&#39;;
        
        // 标题
        $subject = &#39;这里是标题!&#39;;
        
        // 正文
        $content = "您好:\r\n";
        $content .= "   这里是正文\r\n ";
        
        // excel路径
        $filePath = dirname(FILE) . &#39;/excel&#39;;
        $sdate = date(&#39;Y-m-d&#39;);
        $PreName = &#39;CleverCode_&#39; . $sdate;
        
        // 文件名
        $fileName = $filePath . &#39;/&#39; . $PreName . &#39;.xls&#39;;
        
        // 压缩excel文件
        $cmd = "cd $filePath && zip $PreName.zip $PreName.xls";
        exec($cmd, $out, $status);
        $fileList = $filePath . &#39;/&#39; . $PreName . &#39;.zip&#39;;
        
        // 发送邮件(附件为压缩后的文件)
        $ret = SendMail::send($fromAddress, $toAddress, $subject, $content, $fileList);
        if ($ret != &#39;OK&#39;) {
            return $ret;
        }
        
        return &#39;OK&#39;;
    }
}

/**
 * 程序入口
 */
function start(){
    $client = new Client();
    $client->main();
}

start();

?>

Das obige ist der detaillierte Inhalt vonBeispielcode, wie PHP Python aufruft, um schnell E-Mails mit hoher Parallelität zu senden. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn