1. 程式人生 > >Python3筆記-電子郵件的收發

Python3筆記-電子郵件的收發

from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr

import smtplib
#字符集轉換
def __format_addr(s):
	name, addr = parseaddr(s)
	return formataddr((Header(name, 'utf-8').decode(), addr))
#基本資訊初始化
from_addr = input('From: ')
password = input('Password: ')
to_addr = input('To: ')
#使用MIMEMultipart定義Message
msg = MIMEMultipart()
#初始化頭
msg['From'] = __format_addr('Your Dady: <%s>' % from_addr)
msg['To'] = __format_addr('Son: <%s>' % to_addr)
msg['Subject'] = Header('A how are you from......').encode()
#將文字內容新增入郵件
msg.attach(MIMEText('Send with file......', 'plain', 'utf-8'))
#開啟一個圖片檔案,將其新增到郵件中
with open('/Users/zhouming/Desktop/tupian.png', 'rb') as f:
	mime = MIMEBase('image', 'png', filename = 'tupian.png')
	#新增頭部資訊
	mime.add_header('Content-Disposition', 'attachment', filename = 'tupian.png')
	mime.add_header('Content-ID', '<0>')
	mime.add_header('X-Attachment-Id', '0')
	#讀取資訊,預設字符集為空,這裡是圖片就不用設定了
	mime.set_payload(f.read())
	#使用Base64對圖片編碼
	encoders.encode_base64(mime)
	msg.attach(mime)

關於之前的add_header和set_payload函式給出以下文件解釋:

add_header(_name, _value, **_params)
Extended header setting. This method is similar to __setitem__() except that additional header parameters can be provided as keyword arguments. _name is the header field to add and _value is the primary value for the header.

For each item in the keyword argument dictionary _params, the key is taken as the parameter name, with underscores converted to dashes (since dashes are illegal in Python identifiers). Normally, the parameter will be added as key="value" unless the value is None, in which case only the key will be added. If the value contains non-ASCII characters, it can be specified as a three tuple in the format (CHARSET, LANGUAGE, VALUE), where CHARSET is a string naming the charset to be used to encode the value, LANGUAGE can usually be set to None or the empty string (see RFC 2231 for other possibilities), and VALUE is the string value containing non-ASCII code points. If a three tuple is not passed and the value contains non-ASCII characters, it is automatically encoded in RFC 2231 format using a CHARSET of utf-8 and a LANGUAGE of None.

Here’s an example:
msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')

This will add a header that looks like
Content-Disposition: attachment; filename="bud.gif"