手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Python 发送email

[日期:2013-06-24] 来源:Linux社区  作者:ghostid [字体:大 中 小]

以下程序均来自《Python.UNIX和Linux系统管理指南》 http://www.linuxidc.com/Linux/2013-06/86448.htm

sendemail.py

#!/usr/bin/env python

import smtplib

mail_server = 'smtp.163.com'

mail_server_port = 25

from_addr = 'from_username@163.com'

to_addr = 'to_username@163.com'

from_header = 'From: %s\r\n' % from_addr

to_header = 'To: %s\r\n\r\n' % to_addr

subject_header = 'Subject: nothing interesting'

body = 'This is a not very interesting email.'

email_message = '%s\n%s\n%s\n\n%s' %(from_header, to_header, subject_header, body)

s = smtplib.SMTP(mail_server, mail_server_port)

s.set_debuglevel(1)

s.starttls()

s.login("username", "password")

s.sendmail(from_addr, to_addr, email_message)

s.quit()


下面的程序是发送带附件的邮件

email_attachment.py

#!/usr/bin/env python

import email

from email.MIMEText import MIMEText

from email.MIMEMultipart import MIMEMultipart

from email.MIMEBase import MIMEBase

from email import encoders

import smtplib

import mimetypes

mail_server = 'smtp.163.com'

mail_server_port = 25

from_addr = "from_username@163.com"

to_addr = "to_usrename@163.com"

subject_header = 'Subject: Sending PDF Attachment'

attachment = 'disk_report.pdf'

body = '''

this message sends a PDF attachment created with Report Lab.

'''

m = MIMEMultipart()

m['To'] = to_addr

m['From'] = from_addr

m['Subject'] = subject_header

ctype, encoding = mimetypes.guess_type(attachment)

print ctype, encoding

maintype, subtype = ctype.split('/', 1)

print maintype, subtype

m.attach(MIMEText(body))

fp = open(attachment, 'rb')

msg = MIMEBase(maintype, subtype)

msg.set_payload(fp.read())

fp.close()

encoders.encode_base64(msg)

msg.add_header("Content-Disposition", "attachment", filename=attachment)

m.attach(msg)

s = smtplib.SMTP(mail_server, mail_server_port)

s.set_debuglevel(1)

s.starttls()

s.login("username", "password")

s.sendmail(from_addr, to_addr, m.as_string())

s.quit()


效果

linux
相关资讯       email Python 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款