一、发送邮件
Python作为一门强大的编程语言,可以不仅作为数据处理和Web开发的首选,而且还可以通过使用相应的库来发送邮件。Python的smtplib库(简单邮件传输协议库)是发送电子邮件的常用库。大多数邮件服务器都需要经过身份验证才能发送邮件,因此需要在Python代码中添加您的邮件服务器的登录凭据。
下面是一个使用Python发送电子邮件的示例代码:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
msg = MIMEMultipart()
msg['From'] = 'sender_email_address'
msg['To'] = 'recipient_email_address'
msg['Subject'] = 'Subject of the Email'
body = 'This is the body of the email'
msg.attach(MIMEText(body, 'plain'))
filename = 'filename.jpg'
with open(filename, 'rb') as f:
img_data = f.read()
img = MIMEImage(img_data, name=filename)
msg.attach(img)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('sender_email_address', 'sender_email_password')
text = msg.as_string()
server.sendmail('sender_email_address', 'recipient_email_address', text)
server.quit()
在上述代码中,我们使用了SMTP协议发送电子邮件,带有一个附件。可以发现,我们需要登录我们的电子邮件帐户以启用SMTP连接,并使用名为starttls()的方法来启用TLS加密。
发送电子邮件也可以通过其他库,例如yagmail、smtplib等。
二、接收邮件
Python的imaplib(Internet Mail Access Protocol库)是接收电子邮件的常用库,对于使用IMAP(Internet Mail Access Protocol)的大多数邮件服务器,您需要向代码中添加您的邮件服务器的登录凭据。
下面是一个使用Python接收电子邮件列表的示例代码:
import imaplib
import email
import os
user = 'user_email_address'
password = 'user_email_password'
imap_url = 'imap.googlemail.com'
#Establishing the Connection
imap = imaplib.IMAP4_SSL(imap_url)
#Login
imap.login(user, password)
#Fetching the Email Ids
imap.select('Inbox')
status, messages = imap.search(None, 'ALL')
messages = messages[0].split(b' ')
print(messages)
#Iterating through the email ids and storing fetch data in dictionary
for mail in messages:
_, msg = imap.fetch(mail, '(RFC822)')
for response in msg:
if isinstance(response, tuple):
msg = email.message_from_bytes(response[1])
subject = msg['subject']
from_ = msg['from']
print(f'Subject: {subject}')
print(f'From: {from_}')
imap.close()
imap.logout()
在上述代码中,我们使用IMAP协议接收邮件,并显示了每个邮件的主题和发件人的地址。
三、结论
Python的能力不仅仅在于数据处理和Web开发,还包括发送/接收电子邮件。本文演示了如何使用Python中的smtplib和imaplib库来发送和接收电子邮件。
以上是关于利用Python实现邮件发送和接收的方法及代码分享,希望能对初学者或有需要的人有所帮助。
原创文章,作者:OKEL,如若转载,请注明出处:https://www.506064.com/n/145151.html
微信扫一扫
支付宝扫一扫