In the actual development process, there is a high probability of mailbox use. how can I use python to send emails using QQ mail? I have recently encountered this requirement, so I want to share the methods for your convenience. so this article mainly introduces the implementation of using QQ mail to send emails in Python. For more information, see.
Preface
In fact, it is very easy for Python to use QQ mail to send Email code. This function can be implemented in just a few lines of code.
The two modules used are smtplib and email. the methods for these two modules are not described much. Anyone who doesn't know can read this article: using the smtplib and email modules in python to send mail instances
Let's talk about the common methods of sending emails using these two modules on the Internet.
The code is as follows:
import smtplibfrom email.mime.text import MIMETextfrom email.header import Headerdef SendEmail(fromAdd, toAdd, subject, attachfile, htmlText): strFrom = fromAdd; strTo = toAdd; msg =MIMEText(htmlText); msg['Content-Type'] = 'Text/HTML'; msg['Subject'] = Header(subject,'gb2312'); msg['To'] = strTo; msg['From'] = strFrom; smtp = smtplib.SMTP('smtp.qq.com'); smtp.login('501257367@qq.com','password'); try: smtp.sendmail(strFrom,strTo,msg.as_string()); finally: smtp.close;if __name__ == "__main__": SendEmail("501257367@qq.com","501257367@qq.com","","hello","hello world");
Running result:
smtplib.SMTPAuthenticationError: (530, 'Error: A secure connection is requiered(such as ssl). More information at #')
ErrorYou need a secure connection, such as SSL. Therefore, we will use SSL to log on. However, before that, we need to make some preparations, open the QQ mailbox, and click settings.
Account, find POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV service, Enable IMAP/SMTP service, and then send the mobile phone to the specified number as required to obtain the authorization code,
This authorization code is the password to be used for your next logon. the configuration is complete and the code is displayed.
Import smtplibfrom email. mime. text import MIMEText_user = "your QQ mailbox" _ pwd = "your authorization code" _ to = "501257367@163.com" msg = MIMEText ("Test ") msg ["Subject"] = "don't panic" msg ["From"] = _ usermsg ["To"] = _ totry: s = smtplib. SMTP_SSL ("smtp.qq.com", 465) s. login (_ user, _ pwd) s. sendmail (_ user, _ to, msg. as_string () s. quit () print "Success! "Failed t smtplib. SMTPException, e: print" Falied, % s "% e
The running result is as follows:
For more Python-related articles on how to use QQ mail to send emails, please follow the PHP Chinese network!