Reading and parsing email from Gmail using C#, C++ or Python(使用 C#、C++ 或 Python 从 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).
Please, do not use paid libs, and in case of any other libs used, give the download path.
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.
The code can be written in Python or C++, but I prefer it in C#.
Related question:
- 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 '
'.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()
Much of the code above comes from Doug Hellmann's tutorial on imaplib.
这篇关于使用 C#、C++ 或 Python 从 Gmail 读取和解析电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 C#、C++ 或 Python 从 Gmail 读取和解析电子邮件
				
        
 
            
        基础教程推荐
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
 - 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
 - JSON.NET 中基于属性的类型解析 2022-01-01
 - 全局 ASAX - 获取服务器名称 2022-01-01
 - 如何动态获取文本框中datagridview列的总和 2022-01-01
 - 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
 - 首先创建代码,多对多,关联表中的附加字段 2022-01-01
 - 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
 - 错误“此流不支持搜索操作"在 C# 中 2022-01-01
 - 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				