使用python语言发送邮件smtp发送文本和添加附件

使用python语言发送邮件smtp,详细见下面脚本

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

import smtplib
from email.mime.text import MIMEText
from email.header import Header

# 第三方SMTP服务
mail_host = 'smtp.126.com'
mail_user = '[email protected]'
mail_pass = '12345678'

sender = '[email protected]'
receivers = ['[email protected]']

# 三个参数: 第一个为文本内容,第二个plain设置文本格式 ,第三个utf-8设置编码
message = MIMEText('Python 邮件发送测试5。。。', 'plain', 'utf-8')
message['From'] = '[email protected]'   #发送者
message['To'] = '[email protected]'   #接收者

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

smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host, 25)
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
print "邮件发送成功"

注意上面的接收者可以随便填写,可以是数字字符
同时126邮箱要在设置里开通 邮箱授权密码

下面为添加附件的代码:、

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

import smtplib
import email
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication

# 第三方SMTP服务
mail_host = 'smtp.126.com'
mail_user = '[email protected]'
mail_pass = '888888'

sender = '[email protected]'
receivers = ['[email protected]']

#创建一个带附件的实例
message = MIMEMultipart()
message['From'] = '[email protected]'   #发送者
message['To'] = 'weiruoyu魏若愚'   #接收者
# 邮件标题
subject = 'Python SMTP邮件测试带附件。。。'
message['Subject'] = Header(subject, 'utf-8')

#邮件正文内容
message.attach(MIMEText('python含有附件', 'plain', 'utf-8'))

#添加附件
part = MIMEApplication(open('test.txt', 'rb').read())
part.add_header('Content-Disposition', 'attachment', filename="test.txt")
message.attach(part)

#添加附件2
part = MIMEApplication(open('abc.docx', 'rb').read())
part.add_header('Content-Disposition', 'attachment', filename="abc.docx")
message.attach(part)

smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host, 25)
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
smtpObj.quit()

print "邮件发送成功"

上面的filename="test.txt"可以随便自定义的
参考:http://www.runoob.com/python/python-email.html
邮件附件代码参考:http://www.cppcns.com/jiaoben/python/191319.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章