首页 > 编程语言 > 详细

Python 发送邮件脚本

时间:2021-06-07 09:25:59      阅读:20      评论:0      收藏:0      [点我收藏+]
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication


# 文本邮件
def sendEmail():
    host = ‘smtp.163.com‘
    sender = "fzwicc@163.com"
    user = ‘fzwicc@163.com‘
    password = ‘HTSBLLEAVBYJJANH‘  # 授权码
    to = [‘2584066573@qq.com‘]

    # Email 信息
    email = MIMEText("dd", ‘text‘, ‘utf-8‘)
    email[‘Subject‘] = "subject"
    email[‘From‘] = sender
    email[‘To‘] = to[0]
    msg = email.as_string()
    print(msg)
    # 连接
    # 登录
    print(‘Logging with server...‘)
    smtpObj = smtplib.SMTP()
    smtpObj.connect(host, 25)
    smtpObj.login(user, password)
    print(‘Login successful.‘)
    # 发送
    smtpObj.sendmail(sender, to, msg)
    smtpObj.quit()
    print(‘Email has been sent‘)


# 发送附件邮件
def sendEmailWithAttachment():
    host = ‘smtp.163.com‘
    sender = "fzwicc@163.com"
    user = ‘fzwicc@163.com‘
    password = ‘HTSBLLEAVBYJJANH‘  # 授权码
    to = [‘2584066573@qq.com‘]

    # Make content of email
    subject = ‘daily check report‘  # 邮件主题
    with open(‘./file/test.html‘, ‘r‘) as f:
        content = MIMEText(f.read(), ‘html‘, ‘utf-8‘)
        content[‘Content-Type‘] = ‘text/html‘
    # Make txt attachment
    with open(‘./file/txt.md‘, ‘r‘) as f:
        txt = MIMEText(f.read(), ‘plain‘, ‘utf-8‘)
        txt[‘Content-Type‘] = ‘application/octet-stream‘
        txt[‘Content-Disposition‘] = ‘attachment;filename="txt.md"‘
    # Make csv attachment
    part_attach1 = MIMEApplication(open(‘./file/data.csv‘, ‘rb‘).read())  # 打开附件
    part_attach1.set_payload("数据", ‘utf-8‘)
    part_attach1.add_header(‘Content-Disposition‘, ‘attachment‘, filename=‘newName.csv‘)  # 为附件命名v

    # Attach content & attachments to email
    email = MIMEMultipart()
    # email.attach(content)
    # email.attach(txt)
    email.attach(part_attach1)
    email.attach(MIMEText("这里是邮件内容", _subtype=‘html‘, _charset=‘utf-8‘))
    # Settings of the email string
    email[‘Subject‘] = subject
    email[‘From‘] = sender
    email[‘To‘] = to[0]
    msg = email.as_string()
    print(msg)

    # 登录
    print(‘Logging with server...‘)
    smtpObj = smtplib.SMTP()
    smtpObj.connect(host, 25)
    smtpObj.login(user, password)
    print(‘Login successful.‘)

    # 发送
    smtpObj.sendmail(sender, to, msg)
    smtpObj.quit()
    print(‘Email has been sent‘)


# sendEmailWithAttachment()

if __name__ == ‘__main__‘:
    sendEmailWithAttachment()

Python 发送邮件脚本

原文:https://www.cnblogs.com/lymcc/p/14857029.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!