zoukankan      html  css  js  c++  java
  • 用python标准库smtplib来发QQ邮件及Django中发送邮件

    1.QQ邮箱设置

    点击QQ邮箱账号,进入后,开启smtp服务许可:

     点击“生产授权码”,在手机上发送相应的短信,得到授权码。【注意授权码之间没有空格

    2.典型代码块

     
    import smtplib
    from email.mime.text import MIMEText
    from email.header import Header
    msg_from='xxxxxxx@qq.com'  #发送邮件的邮箱号码
    password='xxxxxxx' #授权码,不是邮箱登录密码
    msg_to=['xxx@qq.com','xxx@qq.com','xxx@qq.com'] #收件邮箱List
    message=MIMEText('python邮件发送测试...','plain','utf-8')
    message['From']=Header('来自JohnYang','utf-8')
    message['To']=Header('测试','utf-8')
    message['Subject']=Header('Python SMTP邮件测试','utf-8')
    client=smtplib.SMTP_SSL('smtp.qq.com',smtplib.SMTP_SSL_PORT)
    client.login(msg_from,password)
    client.sendmail(msg_from,msg_to,message.as_string()) #发送
    

      

     3.Django中发送邮件

    Django对smptlib进行了包装,使得发送邮件更为简便。

    首先在settings.py中添加如下设置:

    EMAIL_HOST='smtp.qq.com'
    EMAIL_PORT=25
    EMAIL_HOST_USER='from@example.com'

    EMAIL_HOST_PASSWORD='ixxxxxx'
    EMAIL_USE_TLS=True

    Django中有关邮件的在django.core.mail模块中。

    (1)send_mail

    from django.core.mail import send_mail
    
    send_mail(
        'Subject here',
        'Here is the message.',
        'from@example.com',
        ['to@example.com'],
        fail_silently=False,
    )
    

     (2)send_mass_mail

    datatuple = (
        ('Subject', 'Message.', 'from@example.com', ['john@example.com']),
        ('Subject', 'Message.', 'from@example.com', ['jane@example.com']),
    )
    send_mass_mail(datatuple)
    

      (3)EmailMessage类

    from django.core.mail import EmailMessage
    
    email = EmailMessage(
        'Hello',
        'Body goes here',
        'from@example.com',
        ['to1@example.com', 'to2@example.com'],
        ['bcc@example.com'],
        reply_to=['another@example.com'],
        headers={'Message-ID': 'foo'},
    )
    message.attach_file('/images/weather_map.png')
    message.send()
    

      

    ##### 愿你一寸一寸地攻城略地,一点一点地焕然一新 #####
  • 相关阅读:
    vim的一些基本配置
    做菜好吃的小技巧02
    SQLServer创建用户登录
    Python库整理
    centos7开机界面出现多个选项
    Elasticsearch和MongoDB简要对比
    OLTP与OLAP
    CentOS7命令总结
    windows下快速删除命令
    Idea配置热部署
  • 原文地址:https://www.cnblogs.com/johnyang/p/13550474.html
Copyright © 2011-2022 走看看