首页 > 代码库 > 【python之路14】发送邮件实例

【python之路14】发送邮件实例

1、发邮件的代码

    from email.mime.text import MIMEText
    from email.utils import formataddr
    import smtplib
    msg = MIMEText(‘邮件内容‘,‘plain‘,‘utf-8‘)
    msg[‘from‘] = formataddr([‘sunshuhai‘,‘25193@qq.com‘])
    msg[‘to‘] = formataddr([‘走人‘,‘252222222@qq.com‘])
    msg[‘Subject‘] = ‘主题‘

    server = smtplib.SMTP(‘smtp.qq.com‘,25)
    server.login("25193@qq.com","123456")
    server.sendmail(‘25193@qq.com‘,[‘252222222@qq.com‘,],msg.as_string())
    server.quit()

2、将代码整理为函数

#发送者邮箱地址,接收着邮箱地址,主题,内容,是否发送成功
def send_email(send,receive,subject,concent):
    from email.mime.text import MIMEText
    from email.utils import formataddr
    import smtplib
    ret = True
    try:
        msg = MIMEText(‘邮件内容‘,‘plain‘,‘utf-8‘)
        msg[‘from‘] = formataddr([send])
        msg[‘to‘] = formataddr([‘走人‘,send])
        msg[‘Subject‘] = subject

        server = smtplib.SMTP(‘smtp.qq.com‘,25)
        server.login(send,"123456")
        server.sendmail(send,[receive,],msg.as_string())
        server.quit()
    except:
        ret = False
    return ret

#调用函数
ret = send_email(‘25193@qq.com‘,‘252222222@qq.com‘,‘主题‘,‘hello world!‘)
if ret:
    print(‘发送成功!‘)
else:
    print(‘发送失败!‘)

  

  

【python之路14】发送邮件实例