如何使用POP3_SSL在Python中发送和接收电子邮件
发布时间:2023-12-23 06:31:22
使用POP3_SSL在Python中发送和接收电子邮件可以通过以下步骤完成:
1. 导入所需的模块和库:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import poplib import ssl
2. 设置SMTP服务器和端口号:
smtp_server = "smtp.gmail.com" smtp_port = 465
3. 创建一个MIMEMultipart对象,并设置发件人、收件人和主题:
msg = MIMEMultipart() msg['From'] = 'sender@example.com' msg['To'] = 'receiver@example.com' msg['Subject'] = 'Test Email'
4. 添加邮件正文和附件:
msg.attach(MIMEText('This is a test email.', 'plain'))
# 添加附件
attachment = MIMEText(open('file.txt', 'rb').read())
attachment.add_header('Content-Disposition', 'attachment', filename='file.txt')
msg.attach(attachment)
5. 创建SMTP连接,并登录到邮箱账号:
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, smtp_port, context=context) as server:
server.login('sender@example.com', 'password')
server.sendmail('sender@example.com', 'receiver@example.com', msg.as_string())
6. 使用POP3_SSL连接到收件箱,并登录到邮箱账号:
pop3_server = "pop.gmail.com"
pop3_port = 995
username = 'receiver@example.com'
password = 'password'
context = ssl.create_default_context()
with poplib.POP3_SSL(pop3_server, pop3_port, context=context) as server:
server.user(username)
server.pass_(password)
# 获取邮箱中的邮件数量
num_messages = len(server.list()[1])
# 获取最新的一封邮件并打印
response, lines, octets = server.retr(num_messages)
message_content = b'\r
'.join(lines).decode('utf-8')
print(message_content)
上述代码为简要的示例,可以根据实际需要进行调整和扩展。其中,需要替换相应的发件人、收件人、密码和附件文件名。
这个例子演示了如何使用SMTP_SSL发送带有附件的电子邮件,并使用POP3_SSL接收最新的一封邮件。请确保安装了所需的第三方库:smtplib、email、poplib和ssl。
