smtplib和email,这俩模块是python自带的
SMTP(Simple Mail Transfer Protocol),即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。 python的smtplib提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装。
代码实现 QQ邮箱发送
import smtplib
from email. mime. text import MIMEText
from email. header import Header
from AutoSendEmail. h_test import HT
from AutoSendEmail. config import pwdqq
def send_email ( ) :
sender = 'xxx@qq.com'
receivers = [ 'xxx@qq.com' , 'xxx@qq.com' ]
mail_host = "smtp.qq.com"
mail_user = "383108675@qq.com"
mail_pass = pwdqq
message = MIMEText( HT, 'html' )
message[ 'From' ] = sender
message[ 'To' ] = '1204690031@qq.com'
subject = 'Python SMTP 邮件测试'
message[ 'Subject' ] = '自动脚本发送...'
try :
smtpObj = smtplib. SMTP_SSL( host= mail_host, port= 465 )
smtpObj. connect( mail_host, 465 )
smtpObj. login( mail_user, mail_pass)
smtpObj. sendmail( sender, receivers, message. as_string( ) )
smtpObj. quit( )
print ( "邮件发送成功" )
except Exception as e:
print ( e)
print ( "Error: 无法发送邮件" )
if __name__ == '__main__' :
send_email( )
QQ邮箱设置SMTP服务器,生成授权口令
发送成功实例
代码实现 163邮箱自动发送
import smtplib
from email. mime. text import MIMEText
from AutoSendEmail. config import pwd163
def sentemail ( ) :
host = 'smtp.163.com'
port = 465
sender = 'chengxxx@163.com'
pwd = pwd163
receiver = '1xxx@163.com'
body = '<h1>python script test</h1><p>cd</p>'
msg = MIMEText( body, 'html' )
msg[ 'subject' ] = 'python test'
msg[ 'from' ] = sender
msg[ 'to' ] = receiver
msg[ 'Cc' ] = 'xxx@163.com'
try :
smtp = smtplib. SMTP_SSL( host, port)
smtp. helo( host)
smtp. ehlo( host)
smtp. login( sender, pwd)
smtp. sendmail( sender, receiver, msg. as_string( ) )
print ( 'Done.send email success' )
except smtplib. SMTPException:
print ( 'Error.send email fail' )
if __name__ == '__main__' :
sentemail( )
发送成功