6. 发送邮件

def send_email():
    # smtplib email
    import smtplib
    from email.mime.text import MIMEText
    from email.header import Header
    from email.utils import formataddr

    # 登录
    smtp_obj = smtplib.SMTP('smtp.qq.com')
    smtp_obj.login('360xxxxxx@qq.com', 'xxxxxxxxxxx')

    # 编辑内容
    mail_text = 'This is Email 测试!'
    msg_body = MIMEText(mail_text, 'plain', 'utf-8')

    # 设置从哪发送的
    msg_body['From'] = formataddr((str(Header('Python Email', 'utf-8')), '360xxxxxx@qq.com'))
    msg_body['Subject'] = Header('测试Python自动邮件','utf-8')

    # 发邮件
    smtp_obj.sendmail('360xxxxxx@qq.com', ['xxxxxxxx@qq.com'], msg_body.as_string())

def send_html_email():
    import smtplib
    from email.mime.text import MIMEText
    from email.header import Header
    from email.utils import formataddr

    # 登录
    smtp_obj = smtplib.SMTP('smtp.qq.com')
    smtp_obj.login('360xxxxxx@qq.com', 'xxxxxxxxxx')

    # 编辑内容
    mail_text = '''
    <h1 style="color:red">这是一个HTML邮件</h1>
    <p>这是邮件的主题内容</p>
    <p><a href="https://www.baidu.com">这是一个链接</a></p>
    '''
    msg_body = MIMEText(mail_text, 'html', 'utf-8')

    # 设置从哪发送的
    msg_body['From'] = formataddr((str(Header('Python HTML Email', 'utf-8')), '360xxxxxx@qq.com'))
    msg_body['Subject'] = Header('测试Python HTML邮件','utf-8')

    # 发邮件
    smtp_obj.sendmail('360xxxxxx@qq.com', ['xxxxxxxx@qq.com'], msg_body.as_string())

def send_file_email():
    # smtplib email
    import smtplib
    from email.mime.text import MIMEText
    from email.header import Header
    from email.utils import formataddr
    from email.mime.application import MIMEApplication
    from email.mime.multipart import MIMEMultipart

    # 登录
    smtp_obj = smtplib.SMTP('smtp.qq.com')
    smtp_obj.login('360xxxxxx@qq.com', 'xxxxxxxxxxxxx')

    # 编辑内容
    mail_text = 'This is Email 发送附件测试!'
    msg_body = MIMEText(mail_text, 'plain', 'utf-8')

    # 增加附件
    file = MIMEApplication(open('./办公自动化/files/ppt_test.pptx', 'rb').read())
    file.add_header('Content-Disposition', 'attachment', filename='ppt_test.pptx')

    # 合并所有内容
    multi_part = MIMEMultipart()
    multi_part.attach(msg_body)
    multi_part['From'] = formataddr((str(Header('Python File Email', 'utf-8')), '360xxxxxx@qq.com'))
    multi_part['Subject'] = Header('测试Python 附件邮件','utf-8')
    multi_part.attach(file)

    # 发邮件
    smtp_obj.sendmail('360xxxxxx@qq.com', ['xxxxxxxxxx@qq.com'], multi_part.as_string())

if __name__ == '__main__':
    # send_email()
    # send_html_email()
    send_file_email()