Home  >  Article  >  Backend Development  >  Python method example of sending email using QQ mailbox

Python method example of sending email using QQ mailbox

高洛峰
高洛峰Original
2017-02-13 13:43:221537browse

Preface

In fact, Python is very simple to use QQ mailbox to send Email code. This function can be realized in just a few lines of code.

The modules used are smtplib and email. I won’t say much about the methods of these two modules. Friends who don’t understand can check this article: Example of using smtplib and email modules to send emails in Python

Let’s first talk about the commonly used methods of sending emails using these two modules on the Internet.

The code is as follows:

import smtplib
from email.mime.text import MIMEText
from email.header import Header

def 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 http://www.php.cn/')

Error reporting requires a secure connection, such as SSL, so next we will use SSL to log in, but there Before, we need to make some preparations. Open the qq mailbox, click Settings->

Account, find the POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV service, enable the IMAP/SMTP service, and then according to It is required to use a mobile phone to send to the designated number to obtain the authorization code.


This authorization code is the password you will use to log in next. After the configuration is completed, add the code

import smtplib
from email.mime.text import MIMEText
_user = "你的qq邮箱"
_pwd = "你的授权码"
_to = "501257367@163.com"

msg = MIMEText("Test")
msg["Subject"] = "don't panic"
msg["From"] = _user
msg["To"] = _to

try:
 s = smtplib.SMTP_SSL("smtp.qq.com", 465)
 s.login(_user, _pwd)
 s.sendmail(_user, _to, msg.as_string())
 s.quit()
 print "Success!"
except smtplib.SMTPException,e:
 print "Falied,%s"%e

The running results are as follows:

Python method example of sending email using QQ mailbox

More Python uses QQ mailbox to send emails For articles related to method examples, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn