美文网首页
python发送邮件

python发送邮件

作者: lomidely | 来源:发表于2018-07-11 16:53 被阅读0次

    一: 利用python

    Python分别提供了收发邮件的库,smtplib、poplib和imaplib。

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    
    """
        发送邮件
        :param SMTP_host: smtp.163.com
        :param from_addr: 发送地址:xxx@163.com
        :param password: 邮箱的授权码
        :param to_addrs: 发送给谁的邮箱: xxx@qq.com
        :param subject:  邮件主题: test
        :param content:  邮件内容: test
        :return: None
    """
    
    import smtplib
    import email.mime.multipart
    import email.mime.text
    
    def send_email(SMTP_host, from_addr, password, to_addrs, subject='', content=''):
    
        msg = email.mime.multipart.MIMEMultipart()
        msg['from'] = from_addr
        msg['to'] = to_addrs
        msg['subject'] = subject
        content = content
        txt = email.mime.text.MIMEText(content)
        msg.attach(txt)
    
        smtp = smtplib.SMTP()
        smtp.connect(SMTP_host, '25')
        smtp.login(from_addr, password)
        smtp.sendmail(from_addr, to_addrs, str(msg))
        smtp.quit()
    
    send_email('smtp.163.com', '发件人的163邮箱地址', '163邮箱的授权码', '收件邮箱地址', '主题', '内容')
    

    param password: 邮箱的授权码

    二: 利用shell命令

    1. 安装

    sudo apt-get install mailutils

    2. 使用

    2.1 不带附件

    • 一行命令发送邮件
      mail -s "Test email from ubuntu server!" example@qq.com <<< 'Here is the message body.'

      echo 'Here is the message body.' | mail -s "Test email from ubuntu server!" example@qq.com
      Test email from ubuntu server 是邮件的主题.
      Here is the message body 是邮件的正文.
    • 使用mail的命令提示发送邮件
      peter@qq.com 发送邮件,并抄送给john@qq.com。邮件主题为Test Subject,内容为Merry christmas
      mail -s 'Test Subject' peter@qq.com
      输入该命令后回车,提示Cc:,这时输入抄送邮件地址john@qq.com,然后回车。
      继续输入邮件正文内容Merry christmas,正文输入结束后,按Ctrl-D 结束输入并发送邮件
    • 从文件中读取内容并发送
      mail -s 'Text message' example@qq.com < /home/user/message.txt
      从message.txt中读取内容并发送.
    • 给多个邮箱发送邮件
      mail -s 'Subject' user1@qq.com,user2@qq.com,user3@qq.com < message.txt
    • 指定发件人姓名和地址
      echo "This is the message body" | mail -s "subject" user@qq.com -aFrom:sender@qq.com

      echo "This is the message body" | mail -s "subject" user@qq.com -aFrom:John\<john@qq.com\>

    2.2 带附件

    echo "This is the message body" | mail -s "subject" user@qq.com -A /path/to/attached_file

    相关文章

      网友评论

          本文标题:python发送邮件

          本文链接:https://www.haomeiwen.com/subject/agnhpftx.html