python邮件发送功能

直接上代码

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import smtplib

from email.MIMEText import MIMEText
from email.header import Header

mail_host="mail.picclife.com"
mail_user="devops-notify"
mail_pass="******"


sender = 'devops-notify@picclife.cn'
receivers = ['devops-notify@picclife.cn']

message = MIMEText('Python test...', 'plain', 'utf-8')
message['From'] = Header("test1", 'utf-8')
message['To'] =  Header("test1", 'utf-8')

subject = 'Python SMTP 邮件测试1'
message['Subject'] = Header(subject, 'utf-8')


try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, 25)
    smtpObj.login(mail_user,mail_pass)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print "success"
except smtplib.SMTPException:
    print "Error: "

问题1:命名为email.py时候执行python email.py报错

错误信息如下:

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    import smtplib
  File "/usr/lib64/python2.7/smtplib.py", line 46, in <module>
    import email.utils
  File "/root/email.py", line 5, in <module>
ImportError: No module named mime.text

解决:

  1. 不要将文件命名为email.py
  2. 删除同级目录下的email.py和email.pyc
  3. from email.mine.text import MIMEText 改为 from email.MIMEText import MIMEText

参考:

Python SMTP发送邮件

python 发送邮件及ImportError: No module named mime.text处理

Python-邮件功能:No module named mime.text 的报错问题解决

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐