Python 发送email

本网站用的阿里云ECS,推荐大家用。自己搞个学习研究也不错
以下程序均来自《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.sendma

未经允许不得转载:演道网 » Python 发送email

赞 (0)
分享到:更多 ()

评论 0

评论前必须登录!

登陆 注册