之前发送邮件都是使用Java代码实现的,今天用Python写一个发送邮件的例子,我认为底层原理应该是一样的,都是需要调用到Mail服务器API进行发送邮件。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import smtplib
from email.mime.text import MIMEText
#函数
def sendEmail(toAddr,subject,context):
_msg_from = '123456789@qq.com'
passwd = 'hhvngsvchtapbjia'
_msg_to = toAddr
msg = MIMEText(context)
msg['Subject'] = subject;
msg['From'] = _msg_from
msg['To'] = _msg_to
try:
s = smtplib.SMTP_SSL('smtp.qq.com', 465)
s.login(_msg_from, passwd)
s.sendmail(_msg_from, _msg_to, msg.as_string())
print '发送成功'
except:
print '发送失败'
finally:
s.quit()
#主函数
if __name__ == '__main__':
sendEmail('987654321@qq.com',"请查收Python发的邮件",'Python邮件测试')