侧边栏壁纸
  • 累计撰写 94 篇文章
  • 累计创建 35 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

python发送邮件示例

天明
2023-10-25 / 0 评论 / 0 点赞 / 39 阅读 / 2925 字 / 正在检测是否收录...
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.header import Header

# python 2.3.*: email.Utils email.Encoders
from email.utils import COMMASPACE,formatdate
from email import encoders

import smtplib
import os
import  time

#server['name'], server['user'], server['passwd']
def send_mail(server, fro, to, subject, text, files=[]):
    assert type(server) == dict
    assert type(to) == list
    assert type(files) == list

    msg = MIMEMultipart()
    msg['From'] = fro
    msg['Subject'] = subject
    msg['To'] = COMMASPACE.join(to) #COMMASPACE==', '
    msg['Date'] = formatdate(localtime=True)
    msg.attach(MIMEText(text))

    for file in files:
        part = MIMEBase('application', 'octet-stream') #'octet-stream': binary data
        part.set_payload(open(file, 'rb'.read()))
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
        msg.attach(part)

    import smtplib
    smtp = smtplib.SMTP(server['name'])
    smtp.login(server['user'], server['passwd'])
    smtp.sendmail(fro, to, msg.as_string())
    smtp.close()


sender = 'service@qq.com'
receiver = 'youe@qq.com'
smtpserver = 'smtp.qq.com'
username = 'service@qq.com'
password = 'qq.'
mail_text = "你好"+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
subject=mail_text
msg = MIMEText(mail_text,'text','utf-8')
msg['Subject'] = Header(subject, 'utf-8')
print  'send email from '+sender
print 'send email to '+receiver
print  'send email text '+mail_text
smtp = smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
0

评论区