imap send email by python

本文介绍了如何使用IMAP协议从Gmail邮箱中获取未读邮件,并通过Python代码实现邮件主题的解析。利用IMAP4_SSL连接到pop.gmail.com,登录账户后使用search方法筛选特定日期的邮件,最后提取邮件主题进行打印。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


import imaplib
import email

def extract_body(payload):
    if isinstance(payload,str):
        return payload
    else:
        return '\n'.join([extract_body(part.get_payload()) for part in payload])

conn = imaplib.IMAP4_SSL("pop.gmail.com", 993)
conn.login("user@gmail.com", "password")
#print "logined"
conn.select()
#typ, data = conn.search(None, 'UNSEEN')
typ, data = conn.search(None, '(SINCE "3-Aug-2011")')
#typ, data = conn.search(None, 'OR')
#typ, data = conn.search(None, '')
try:
    for num in data[0].split():
        typ, msg_data = conn.fetch(num, '(RFC822)')
        for response_part in msg_data:
            if isinstance(response_part, tuple):
                msg = email.message_from_string(response_part[1])
                subject=msg['subject']                   
                print(subject)
                #payload=msg.get_payload()
                #body=extract_body(payload)
                #print(body)
                #if 
                #conn.store(num, '+FLAGS', '\\Deleted')
        #conn.store(num, '+FLAGS', '\\Deleted')
        #conn.expunge()
        #typ, response = conn.store(num, '+FLAGS', r'(\Seen)')


#typ, data = M.search(None, 'ALL')
#for num in data[0].split():
   #M.store(num, '+FLAGS', '\\Deleted')
#M.expunge()

finally:
    try:
        conn.close()
    except:
        pass
    conn.logout()

imap protocol is here:

http://tools.ietf.org/html/rfc3501.html#page-35

IMAP search critera strings is here:

http://www.example-code.com/csharp/imap-search-critera.asp

IMAP Search Keys are as follows:

      ALL
         All messages in the mailbox; the default initial key for
         ANDing.

      ANSWERED
         Messages with the \Answered flag set.

      BCC 
         Messages that contain the specified string in the envelope
         structure's BCC field.

      BEFORE 
         Messages whose internal date (disregarding time and timezone)
         is earlier than the specified date.

      BODY 
         Messages that contain the specified string in the body of the
         message.

      CC 
         Messages that contain the specified string in the envelope
         structure's CC field.

      DELETED
         Messages with the \Deleted flag set.

      DRAFT
         Messages with the \Draft flag set.

      FLAGGED
         Messages with the \Flagged flag set.

      FROM 
         Messages that contain the specified string in the envelope
         structure's FROM field.

      HEADER  
         Messages that have a header with the specified field-name (as
         defined in [RFC-2822]) and that contains the specified string
         in the text of the header (what comes after the colon).  If the
         string to search is zero-length, this matches all messages that
         have a header line with the specified field-name regardless of
         the contents.

      KEYWORD 
         Messages with the specified keyword flag set.

      LARGER 
         Messages with an [RFC-2822] size larger than the specified
         number of octets.

      NEW
         Messages that have the \Recent flag set but not the \Seen flag.
         This is functionally equivalent to "(RECENT UNSEEN)".

      NOT 
         Messages that do not match the specified search key.

      OLD
         Messages that do not have the \Recent flag set.  This is
         functionally equivalent to "NOT RECENT" (as opposed to "NOT
         NEW").

      ON 
         Messages whose internal date (disregarding time and timezone)
         is within the specified date.

      OR  
         Messages that match either search key.

      RECENT
         Messages that have the \Recent flag set.

      SEEN
         Messages that have the \Seen flag set.

      SENTBEFORE 
         Messages whose [RFC-2822] Date: header (disregarding time and
         timezone) is earlier than the specified date.

      SENTON 
         Messages whose [RFC-2822] Date: header (disregarding time and
         timezone) is within the specified date.

      SENTSINCE 
         Messages whose [RFC-2822] Date: header (disregarding time and
         timezone) is within or later than the specified date.

      SINCE 
         Messages whose internal date (disregarding time and timezone)
         is within or later than the specified date.

      SMALLER 
         Messages with an [RFC-2822] size smaller than the specified
         number of octets.

      SUBJECT 
         Messages that contain the specified string in the envelope
         structure's SUBJECT field.

      TEXT 
         Messages that contain the specified string in the header or
         body of the message.

      TO 
         Messages that contain the specified string in the envelope
         structure's TO field.

      UID 
         Messages with unique identifiers corresponding to the specified
         unique identifier set.  Sequence set ranges are permitted.

      UNANSWERED
         Messages that do not have the \Answered flag set.

      UNDELETED
         Messages that do not have the \Deleted flag set.

      UNDRAFT
         Messages that do not have the \Draft flag set.

      UNFLAGGED
         Messages that do not have the \Flagged flag set.

      UNKEYWORD 
         Messages that do not have the specified keyword flag set.

      UNSEEN
         Messages that do not have the \Seen flag set.




### 如何使用 Python 发送 QQ 邮箱邮件 为了利用 Python 向 QQ 邮箱发送邮件,需先配置好 SMTP 服务并获取授权码。具体操作如下: #### 开启 QQ 邮件的 SMTP 服务 前往 QQ 邮箱的安全设置页面启用 POP3/IMAP 和 SMTP 功能,并申请独立密码用于第三方客户端登录[^1]。 #### 编写 Python 脚本发送邮件 下面是一个完整的例子展示怎样借助 `smtplib` 及 `email.mime.text.MIMEText` 来构建一封简单的纯文本邮件并通过 SSL 加密方式提交给 QQ 的 SMTP 服务器: ```python import smtplib from email.mime.text import MIMEText # 定义发信者、收信者、主题和正文内容 sender = 'your_qq_number@qq.com' receivers = ['receiver@example.com'] subject = "Test Mail" content = "This is a test mail sent by python script." # 构建消息体 msg = MIMEText(content,'plain','utf-8') msg['Subject'] = subject msg['From'] = sender msg['To'] = ','.join(receivers) try: # 创建SSL加密通道连接到QQ邮箱SMTP服务器 server = smtplib.SMTP_SSL("smtp.qq.com", 465) # 登录账号 (注意这里不是直接输入明文密码而是之前获得的应用专属密码) login_result = server.login(sender, "your_authorization_code") # 如果成功则返回(235, b'Authentication successful')表示认证通过 if login_result and int(login_result[0]) == 235: # 执行发送动作并将状态码存入变量result中 result = server.sendmail(sender, receivers, msg.as_string()) # 成功会得到一个空字典{} print('Email has been send successfully.' if not result else f'Send failed:{str(result)}') finally: # 关闭链接 server.quit() ``` 此段代码实现了向指定地址发送一封简单的内容为 “This is a test mail...” 的测试邮件的功能[^4]。 关于 **接收** QQ 邮箱中的邮件,则通常涉及到 IMAP 协议而不是 SMTP。这超出了当前讨论范围,在此不做赘述。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值