怎么用python收发邮件

   2025-02-15 3990
核心提示:要使用Python收发邮件,你可以使用内置的smtplib和poplib模块来发送和接收邮件。下面是一个简单的示例:发送邮件:import smtpli

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

发送邮件:

import smtplibfrom email.mime.text import MIMETextdef 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 poplibfrom email.parser import Parserdef 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访问。

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

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言