如何用python自动发送邮件
2017-08-26 · 百度知道合伙人官方认证企业
注意如果使用qq的smtp转发功能的话,需要在设置页面中将该功能打开,然后设定密码,改密码就是赋值给下文password中的。
开启smtp转发功能文档
[python] view plain copy
#from email.MIMEText import MIMEText #old version cannot recongnize by new python
from email.MIMEText import MIMEText
from email.Header import Header
msg = MIMEText('hello, send by python','plain','utf-8');
from_addr = "*****@qq.com" #email addresss include domain name
password = "******" #password
to_addr = "****@qq.com" # target email address
smtp_server = "smtp.qq.com" #smtp sever domain for qq is smtp.qq.com
import smtplib
server = smtplib.SMTP(smtp_server,25);
server.set_debuglevel(1)
server.login(from_addr,password);
server.sendmail(from_addr,[to_addr], msg.as_string())
server.quit()
上面这个是没有主题的,有主题的话建议采用下面这个代码
下面是连续发送有主题的文件10封
[python] view plain copy
from email.Header import Header
from email.MIMEText import MIMEText
from email import encoders
from email.utils import parseaddr, formataddr
import smtplib
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))
from_addr = "*****@qq.com" #email addresss include domain name
password = "******" #password
to_addr = "****@qq.com" # target email address
smtp_server = "smtp.qq.com" #smtp sever domain for qq is smtp.qq.com
for num in range(1,11):
msg = MIMEText('hello, send by Tom', 'plain', 'utf-8');
msg['From'] = _format_addr('Tom <%s>' % from_addr)
msg['To'] = _format_addr('addministrator <%s>' % to_addr)
msg['Subject'] = Header('The greeting from Tom','utf-8').encode()
server = smtplib.SMTP(smtp_server,25)
server.set_debuglevel(1)
server.login(from_addr, password)
#server.sendmail(from_addr, [to_addr], msg.as_string())
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()