怎么用python收发邮件

avatar
作者
筋斗云
阅读量:0

要使用Python收发邮件,你可以使用内置的smtplibpoplib模块来发送和接收邮件。下面是一个简单的示例:

发送邮件:

import smtplib from email.mime.text import MIMEText  def send_email(sender_email, receiver_email, subject, message, password):     # 创建邮件内容     email_message = MIMEText(message)     email_message['Subject'] = subject     email_message['From'] = sender_email     email_message['To'] = receiver_email      # 发送邮件     with smtplib.SMTP('smtp.gmail.com', 587) as smtp:         smtp.starttls()         smtp.login(sender_email, password)         smtp.send_message(email_message) 

接收邮件:

import poplib from email.parser import Parser  def receive_email(receiver_email, password):     # 连接到POP3服务器     with poplib.POP3('pop.gmail.com') as pop:         pop.user(receiver_email)         pop.pass_(password)          # 获取邮件列表         email_list = pop.list()[1]         for email_info in email_list:             email_number, _ = email_info.decode().split(' ')             email_number = int(email_number)              # 获取邮件内容             _, lines, _ = pop.retr(email_number)             email_content = b'\r\n'.join(lines).decode('utf-8')              # 解析邮件内容             email = Parser().parsestr(email_content)              # 打印邮件主题和发件人             print("主题:", email['Subject'])             print("发件人:", email['From']) 

注意:在发送邮件之前,你需要在发件人的邮箱设置中启用SMTP访问,并生成一个应用密码(如果使用Gmail)。

在接收邮件之前,你需要在收件人的邮箱设置中启用POP3访问。

你可以根据需要对以上代码进行修改和扩展。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!