歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Python 發送email

以下程序均來自《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 = '[email protected]'

to_addr = '[email protected]'

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 = "[email protected]"

to_addr = "[email protected]"

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()


效果

Copyright © Linux教程網 All Rights Reserved