1 Introduction
Sending messages in PHP is usually a matter of encapsulating a PHP SMTP message class to send messages. But PHP's underlying socket programming is very inefficient relative to python. Clevercode also wrote crawler crawling Web pages written in Python, and crawling Web pages with a crawler written in PHP. found that although the use of PHP Curl crawl Web pages, but involves timeouts, multi-threaded simultaneous crawl and so on. I have to say that Python is much better at network programming than PHP.
When sending mail, PHP writes its own SMTP class, which is sent with low efficiency and speed. Especially when sending a large number of messages with attachment reports. PHP is inefficient. It is recommended that you use PHP to call Python in a way that sends messages.
2 Program 2.1 Python Program
The PHP program and the Python file must be the same encoding. such as are GBK number, or UTF-8 encoding at the same time, otherwise prone to garbled. Python sends mail mainly using the email module. Here the Python files and PHP files are GBK encoded, sent the message header content and the body content is also GBK encoded.
#!/usr/bin/python#-*-coding:gbk-*-"" "Mail Send Class" "# mail.py## Copyright (c) by http://blog.csdn.net/CleverCode## mo Dification history:#--------------------# 2014/8/15, by Clevercode, Createimport threadingimport timeimport randomfrom Email. Mimetext Import mimetextfrom Email. Mimemultipart Import mimemultipartfrom Email. Mimebase Import mimebasefrom Email import Utils, encodersimport mimetypesimport sysimport smtplibimport socketimport Geto Ptimport osclass sendmail:def __init__ (Self,smtpserver,username,password): "" "SMTPSERVER:SMTP server, Username: Login name, password: login password "" "Self.smtpserver = smtpserver Self.username = Username Self.password = password def genmsginfo (Self,fromaddress,toaddress,subject,content,filelist, Subtype = ' plain ', CharSet = ' gb2312 '): "" "Combo Message Send Package fromaddress: sender, Toaddress: Recipient, Subject: Title, Content: Body, fileList: attachment, SubType:plain or HTML charset: Encode "" "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:li STARR = Filelist.split (', ') for item in Listarr: #文件是否存在 if OS.PA Th.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 () d EF Send (self,fromaddress,toaddress,subject = none,content = None,filelist = None, subtype = ' plain ', CharSet = ' gb2312 '): "" "Mail send function fromaddress: sender, Toaddress: Recipient, Subject: Title content: Body FileList: Attachment list subtype:plain or HTML charset: Encode "" "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,cont Ent,filelist,subtype,charset)) #退出 server.quit () except (SOCKET.GAIERROR,SOCKET.E Rror,socKet.herror,smtplib. smtpexception), E:return "Error:your Mail Send failed!", e return ' OK ' def usage (): "" "to make With help "" "Print" "" useage:%s [-h]-S <smtpServer>-u <username>-P <password>-F <fromAddress> -T <toAddress> [-S <subject>-C <content>-f <filelist>] Mandatory arguments to Lo NG options is 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 ' s address. -T "[email protected],[email protected]". -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 = Non E 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 n Ame 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"): File List = value if SmtpServer = = None or username = = None or password = = None:print ' SmtpServer or username or Password can not be empty! ' Sys.exit (3) mail = SendMail (smtpserver,username,password) ret = Mail.send (fromaddress,toaddress,subje ct,content,filelist) if ret! = ' OK ': Print ret sys.exit (4) print ' OK ' return ' OK ' I F __name__ = = ' __main__ ': Start ()
2.2 Python program use help input the following command, you can output the use of this program Help # python mail.py--help
2.3 PHP Program This program is mainly PHP splicing command string, called Python program. Note: The program sends the mail, needs to the mail service provider, opens the STMP service function. If QQ needs to turn on SMTP function, can use the program to send mail. Open as.
The PHP calling program is as follows:
<?php/** * sendmail.php * * Send mail class * * Copyright (c) by Http://blog.csdn.net/CleverCode * * Modification History: *--------------------* 2015/5/18, by Clevercode, Create * */class sendmail{/** * Send Mail method * * @param strin G $fromAddress sender, ' [email protected] ' or modify the sender's name ' clevercode<[email protected]> ' @param string $toAdd Ress recipient, multiple recipients comma separated, ' [email protected],[email protected],[email protected] ', or ' test1<[email protected]>,test2<[email protected]>,.... ' * @param string $subject title * @param string $conten T body * @param string $fileList attachment, the attachment must be an absolute path, and multiple attachments are separated by commas. '/data/test1.txt,/data/test2.tar.gz,... ' * @return string successfully returned ' OK ', failure returned error message */public static function send ($fro Maddress, $toAddress, $subject = null, $content = NULL, $fileList = null) {if (strlen ($fromAddress) < 1 | | strle N ($toAddress) < 1) {return ' $fromAddress or $toAddress can not be empty! '; } SMTP Server $smtpServer = ' smtp.qq.com '; Login user $username = ' [email protected] '; Login password $password = ' 123456 '; Stitching the command string, is actually called/home/clevercode/mail.py $cmd = "Lang=c &&/usr/bin/python/home/clevercode/mail.py"; $cmd. = "-S ' $smtpServer '"; $cmd. = "-U ' $username '"; $cmd. = "-P ' $password '"; $cmd. = "-F ' $fromAddress '"; $cmd. = "-T ' $toAddress '"; if (Isset ($subject) && $subject! = NULL) {$cmd. = '-S ' $subject ' "; } if (Isset ($content) && $content! = NULL) {$cmd. = "-C ' $content '"; } if (Isset ($fileList) && $fileList! = NULL) {$cmd. = "-F ' $fileList '"; }//execute command EXEC ($cmd, $out, $status); if ($status = = 0) {return ' OK '; } else {return ' error,send Mail, $fromAddress, $toAddress, $SUBJECT, $content, $fileList "; } return ' OK '; }}
2.3 Use the sample to compress Excel into an attachment and send the message.
<?php/** * test.php * * Compress Excel into attachments, send mail * * Copyright (c) http://blog.csdn.net/CleverCode * * Modification history : *--------------------* 2015/5/14, by Clevercode, Create * */include_once (' sendmail.php ');/* Client class * To isolate the client and business logic as possible, Reduce the coupling between page logic and business logic algorithms, * make the algorithm of business logic more portable */class client{public Function main () {//Sender $fromAddress = ' Clevercode<[email protected]> '; Receiver $toAddress = ' [email protected] '; Title $subject = ' Here is the title! '; Text $content = "Hello: \ r \ n"; $content. = "Here is the body \ r \ n"; Excel Path $filePath = dirname (__file__). '/excel '; $sdate = Date (' y-m-d '); $PreName = ' Clevercode_ '. $sdate; File name $fileName = $filePath. '/' . $PreName. '. xls '; Compress Excel Files $cmd = "CD $filePath && zip $PreName. zip $PreName. xls"; EXEC ($cmd, $out, $status); $fileList = $filePatH. '/' . $PreName. '. zip '; Send mail (attached as compressed file) $ret = Sendmail::send ($fromAddress, $toAddress, $subject, $content, $fileList); if ($ret! = ' OK ') {return $ret; } return ' OK '; }}/** * Program Entry */function start () {$client = new client (); $client->main ();} Start ();? >
2.4 Program source code download http://download.csdn.net/detail/clevercode/8711809
Copyright Notice:
1) original works, from "Clevercode's blog" , please be sure to mention the following original address when reproduced , otherwise hold the copyright legal responsibility.
2) Original address : http://blog.csdn.net/clevercode/article/details/45815453 ( reprint must indicate this address ).
3) welcome everyone to pay attention to my blog more wonderful content: Http://blog.csdn.net/CleverCode.
PHP calls Python to send mail