python smtplib发送邮件
最近看到了一个防止DDOS的python脚本,不过其邮件通知功能一直不成功,而最近又在学习python 。打开源码查看,发现有调用smtplib 进行邮件发送 。不过因为里面有调用配置文件参数,略有点复杂。先从网上查了查smtplib的用法 。通过smtplib进行gmail发送代码示例:
1#!/usr/bin/env python
2import smtplib
3import sys
4import email.mime.text
5# my test mail
6mail_username='[email protected]'
7mail_password='test'
8from_addr = mail_username
9to_addrs=('[email protected]')
10# HOST & PORT
11HOST = 'smtp.gmail.com'
12PORT = 25
13# Create SMTP Object
14smtp = smtplib.SMTP()
15print 'connecting ...'
16# show the debug log
17smtp.set_debuglevel(1)
18# connet
19try:
20 print smtp.connect(HOST,PORT)
21except:
22 print 'CONNECT ERROR ****'
23# gmail uses ssl
24smtp.starttls()
25# login with username & password
26try:
27 print 'loginning ...'
28 smtp.login(mail_username,mail_password)
29except:
30 print 'LOGIN ERROR ****'
31# fill content with MIMEText's object
32msg = email.mime.text.MIMEText('Hi ,this is a test mail')
33msg['From'] = from_addr
34msg['To'] = ';'.join(to_addrs)
35msg['Subject']='hello , today is a special day'
36print msg.as_string()
37smtp.sendmail(from_addr,to_addrs,msg.as_string())
38smtp.quit()
代码挺简单,使用时,只需要把用户、密码、收件人、主题及内容更换即可。
捐赠本站(Donate)
如您感觉文章有用,可扫码捐赠本站!(If the article useful, you can scan the QR code to donate))
- Author: shisekong
- Link: https://blog.361way.com/smtplib/1922.html
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.