python从base64解码电子邮件

2024-04-29 18:53:18 发布

您现在位置:Python中文网/ 问答频道 /正文

hello iam使用python脚本从特定地址邮件中获取消息似乎一切正常,但我对可打印结果有一个问题,那就是base64代码。 我想解码的结果,以获得解码消息时,做打印的最终结果,请帮助!! 已经谢谢了

使用的代码

# Importing libraries 
import imaplib, email 

user = 'USER_EMAIL_ADDRESS'
password = 'USER_PASSWORD'
imap_url = 'imap.gmail.com'

# Function to get email content part i.e its body part 
def get_body(msg): 
    if msg.is_multipart(): 
        return get_body(msg.get_payload(0)) 
    else: 
        return msg.get_payload(None, True) 

# Function to search for a key value pair 
def search(key, value, con): 
    result, data = con.search(None, key, '"{}"'.format(value)) 
    return data 

# Function to get the list of emails under this label 
def get_emails(result_bytes): 
    msgs = [] # all the email data are pushed inside an array 
    for num in result_bytes[0].split(): 
        typ, data = con.fetch(num, 'BODY.PEEK[1]') 
        msgs.append(data) 

    return msgs 

# this is done to make SSL connnection with GMAIL 
con = imaplib.IMAP4_SSL(imap_url) 

# logging the user in 
con.login(user, password) 

# calling function to check for email under this label 
con.select('Inbox') 

# fetching emails from this user "tu**h*****1@gmail.com" 
msgs = get_emails(search('FROM', 'MY_ANOTHER_GMAIL_ADDRESS', con)) 

# Uncomment this to see what actually comes as data 
# print(msgs) 


# Finding the required content from our msgs 
# User can make custom changes in this part to 
# fetch the required content he / she needs 

# printing them by the order they are displayed in your gmail 
for msg in msgs[::-1]: 
    for sent in msg: 
        if type(sent) is tuple: 

            # encoding set as utf-8 
            content = str(sent[1], 'utf-8') 
            data = str(content) 

            # Handling errors related to unicodenecode 
            try: 
                indexstart = data.find("ltr") 
                data2 = data[indexstart + 5: len(data)] 
                indexend = data2.find("</div>") 

                # printtng the required content which we need 
                # to extract from our email i.e our body 
                print(data2[0: indexend]) 

            except UnicodeEncodeError as e: 
                pass

结果打印出来了

'''

AGVSBG8GD29YZCBPYW0GDGHLIG1LC3NHZ2UGZNJVBSBWFPBA==

'''


Tags: thetoinfordatagetreturnemail
1条回答
网友
1楼 · 发布于 2024-04-29 18:53:18

您可以使用base64module来解码base64编码的字符串:

import base64

your_string="aGVsbG8gV29ybGQ==" # the base64 encoded string you need to decode
result = base64.b64decode(your_string.encode("utf8")).decode("utf8")
print(result) 

根据mCoding的建议,编码从ASCII改为utf-8

相关问题 更多 >