菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
243
0

Python 发送邮件脚本

原创
05/13 14:22
阅读数 94618
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 = ''  # 授权码
    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()

发表评论

0/200
243 点赞
0 评论
收藏