在按照在线教程后,我一直在使用Python中的小型电子邮件实用程序。唯一的问题似乎是我打印的数据是None
。例如,电子邮件的发件人和主题在打印时为None
。这是我的代码:
import imaplib
import email
class email_account:
#u: email username
#domain: email domain
#pwd: email account password
#smtp_server: SMTP server for email account. I.e. "imap.gmail.com"
#smtp_port: SMTP server port number. I.e. 993
def __init__(self, u, domain, pwd, smtp_server, smtp_port):
self.u = u
self.domain = domain
self.pwd = pwd
self.smtp_server = smtp_server
self.smtp_port = smtp_port
#extracts information from an email
def read_email(self, mail):
return None
#open the inbox for the email account and get the IDs of all emails
def open_inbox(self, mail):
mail.select("inbox")
type, data = mail.search(None, "all")
mail_ids = data[0]
id_list = mail_ids.split()
#get ID of first and last email
first_id = int(id_list[0])
last_id = int(id_list[-1])
print("First ID: " + str(first_id) + " -> " + str(int(last_id)))
#iterate through all emails retrieved from the inbox
for x in range(first_id, last_id, 1):
print("RAN")
t, d = mail.fetch(str(x), "(RFC822)")
for message_parts in d:
print(isinstance(message_parts[1], str))
message = email.message_from_string(str(message_parts[1]))
subject = message["subject"]
sender = message["from"]
print("From: " + str(sender) + "\n")
print("Subject: " + str(subject) + "\n")
#login to the email account with the provided credentials
def login(self):
mail = imaplib.IMAP4_SSL(self.smtp_server)
mail.login(self.u, self.pwd)
self.open_inbox(mail)
new_email = email_account("my_email", "@gmail.com", "password", "imap.gmail.com", 993)
new_email.login()
'print(“发件人:”+ str(发件人)+“\ n”)'打印出From: None
,print("Subject: " + str(subject) + "\n")
打印出Subject: None
。这是怎么回事?