使用C#,C ++或Python从Gmail读取和解析电子邮件 [英] Reading and parsing email from Gmail using C#, C++ or Python

查看:144
本文介绍了使用C#,C ++或Python从Gmail读取和解析电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须做一个Windows应用程序,可以随时访问Gmail帐户,并检查是否有新的电子邮件。如果有的话,它必须阅读电子邮件正文和主题(简单的文本电子邮件,没有图像或附件)。

I have to do a Windows application that from times to times access a Gmail account and checks if there is a new email. In case there is, it must read the email body and subject (a simple text email, without images or attachments).

请不要使用付费的libs使用任何其他库的情况,给出下载路径。

Please, do not use paid libs, and in case of any other libs used, give the download path.

我需要电子邮件正文和主题。因此,如果来自Gmail的长而复杂的消息可以被解析,只有两个字符串包含主题和正文,那将是完美的。

And I need the email body and subject only. So if the long and complex message that comes from Gmail could be parsed and only two strings containing the subject and the body, it would be perfect.

最后,我只有从上次执行以来获得新消息到达。因此,读取的消息可以被标记为读取,并且仅考虑新消息(标记为新)。

Finally, I only have to get the new messages arrived since the last execution. So the read messages could be marked as "read" and only the new ones (marked as "new") are considered.

代码可以用Python或C ++编写,但我更喜欢C#。

The code can be written in Python or C++, but I prefer it in C#.

相关问题:

  • Properly formatted example for Python iMAP email access?

推荐答案

这将打印出不可见信息的主体和正文,并标记出所见的消息。

This prints the subject and body of unseen messages, and marks those messages as seen.

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("imap.gmail.com", 993)
conn.login("user", "password")
conn.select()
typ, data = conn.search(None, 'UNSEEN')
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)
        typ, response = conn.store(num, '+FLAGS', r'(\Seen)')
finally:
    try:
        conn.close()
    except:
        pass
    conn.logout()

上面的大部分代码来自 Doug Hellmann关于imaplib的教程

Much of the code above comes from Doug Hellmann's tutorial on imaplib.

这篇关于使用C#,C ++或Python从Gmail读取和解析电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆