python实现发送邮件【超简单】

python实现发送邮件【超简单】python如何发送邮件(使用QQ邮箱)

1、只发送信息
def send_msg(msg):
    my_sender = '[email protected]'  # 发件人邮箱账号
    my_pass = 'krbbydaossjobjfa'  # 发件人邮箱授权码!! 这里不是密码!!
    to_user = '[email protected]'  # 收件人邮箱账号,我这边发送给自己

 	msg = msg  # 要发的信息

    # 登陆邮箱
    sent = smtplib.SMTP()
    sent.connect('smtp.qq.com', 25)
    mail_name = my_sender  # 发送人邮箱地址
    mail_password = my_pass  # 注意:这里不是密码,而应该填写授权码!!
    sent.login(mail_name, mail_password)  # 登陆

    # 编辑邮件内容
    to_user_list = [to_user]  # 收件人邮箱地址
    content = MIMEText(msg)  # 正文内容

    content['From'] = 'xs'  # 发件人
    content['Subject'] = 'XS-ID'  # 邮件标题
    content['To'] = ','.join(to_user_list)  # 收件人,用逗号连接多个邮件,实现群发

    # 发送邮件
    try:
        sent.sendmail(mail_name, to_user_list, content.as_string())  # 3个参数 发送人,收件人,邮件内容
        print('Success')
        sent.close()
    except smtplib.SMTPException:
        print("Error:Fail")
        
if __name__ == '__main__':
	msg = '你是大好人!'
 	send_msg(msg):
2、发送带有附件的邮箱
def send_att(msg):

    my_sender = '[email protected]'  # 发件人邮箱账号
    my_pass = 'krbbydaossjobjfa'  # 发件人邮箱授权码!! 这里不是密码!!
    to_user = '[email protected]'  # 收件人邮箱账号,我这边发送给自己

    msg = msg

    # 登陆邮箱
    sent = smtplib.SMTP()
    sent.connect('smtp.qq.com', 25)
    mail_name = my_sender  # 发送人邮箱地址
    mail_password = my_pass  # 注意:这里不是密码,而应该填写授权码!!
    sent.login(mail_name, mail_password)  # 登陆

    # 编辑邮件内容
    to_user_list = [to_user]  # 收件人邮箱地址
    message = MIMEMultipart()
    message['From'] = Header('XS', 'utf-8')
    message['Subject'] = Header('xxss', 'utf-8')
    message['To'] = Header("User", 'utf-8')
    message.attach(MIMEText(msg, 'plain', 'utf-8'))

    # 添加附件1
    try:
        send_file = './test.csv'
        att1 = MIMEText(open(send_file).read(), 'base64', 'utf-8')
        att1["Content-Type"] = 'application/octet-stream'
        att1["Content-Disposition"] = 'attachment; filename="test.csv"'      # 这里的filename是邮件中显示什么名字
        message.attach(att1)
    except Exception:
        print('发送邮件时,文件不存在。。')


    try:
        sent.sendmail(mail_name, to_user_list, message.as_string())  # 3个参数 发送人,收件人,邮件内容
        print('Success')
        sent.close()
    except smtplib.SMTPException:
        print("Error:Fail")
if __name__ == '__main__':
	msg = '你是大好人!'
 	send_att(msg):

3、QQ邮箱如何开启授权码

参考:https://blog.csdn.net/weixin_44915703/article/details/104417030

你可能感兴趣的:(python,python,http)