Python发送邮件完整示例
只发送正文
下面是以网易 yeah.net 邮箱为例子。
from email.header import Header
from email.mime.text import MIMEText
import smtplib
to = ['xxx@qq.com', 'xxx@163.com']
from_address = 'username@yeah.net'
from_password = 'xxxxxx'
smtp_server = 'smtp.yeah.net'
# 纯文本邮件
# msg = MIMEText('我是正文啊。。', 'plain', 'utf-8')
# HTML 邮件
msg = MIMEText('<html><body><h1>Hello</h1>' +
'<p>send by <a href="http://www.python.org">Python网站</a>...</p>' +
'</body></html>',
'html',
'utf-8')
msg['From'] = from_address
msg['To'] = ",".join(to)
msg['Subject'] = Header('我是主题啊。。', 'utf-8').encode()
server = smtplib.SMTP(smtp_server, 25)
server.set_debuglevel(1)
server.login(from_address, from_password)
server.sendmail(from_address, to, msg.as_string())
server.quit()
正文和附件同时发送
同样是以网易 yeah.net 邮箱为例子。
from email import encoders
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
to = ['xxx@qq.com', 'xxx@163.com']
from_address = 'username@yeah.net'
from_password = 'xxxxxx'
smtp_server = 'smtp.yeah.net'
# 邮件对象
msg = MIMEMultipart()
msg['From'] = from_address
msg['To'] = ",".join(to)
msg['Subject'] = Header('我是主题啊。。', 'utf-8').encode()
# 邮件正文
msg.attach(MIMEText('send with file 有附件的邮件...', 'plain', 'utf-8'))
# 添加附件
for filename in ['/Users/yzy/.vimrc', '/Users/yzy/.bash_profile']:
with open(filename, 'rb') as f:
mime = MIMEBase("application", "octet-stream")
mime.add_header('Content-Disposition', 'attachment', filename=filename.split("/")[-1])
mime.set_payload(f.read())
encoders.encode_base64(mime)
msg.attach(mime)
server = smtplib.SMTP(smtp_server, 25)
server.set_debuglevel(1)
server.login(from_address, from_password)
server.sendmail(from_address, to, msg.as_string())
server.quit()