如何从Python代码发送邮件?

0 投票
1 回答
54 浏览
提问于 2025-04-13 13:31

这个邮件包提供了以下代码:

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.message import EmailMessage

# Open the plain text file whose name is in textfile for reading.
with open(textfile) as fp:
    # Create a text/plain message
    msg = EmailMessage()
    msg.set_content(fp.read())

# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = f'The contents of {textfile}'
msg['From'] = me
msg['To'] = you

# Send the message via our own SMTP server.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()

我做了一些小改动,想给自己发一封“你好,世界”的邮件:

import smtplib
from email.message import EmailMessage

msg = EmailMessage()
msg.set_content("Hello")

msg['Subject'] = 'test mail'
msg['From'] = 'personnal.mail@gmail.com'
msg['To'] = 'personnal.mail@gmail.com'

# Send the message via our own SMTP server.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()

(这里的邮件内容已经做了匿名处理)

但是我遇到了以下错误:

[Errno 99] Cannot assign requested address

有人能告诉我应该怎么做才能让这个工作吗?

1 个回答

2

你的问题是,发送邮件需要一个服务器来管理通信,这个服务器叫做SMTP服务器。

如果你使用的是Gmail账号,就需要用谷歌的SMTP服务器。

下面是一个如何使用它的例子:

import smtplib
from email.mime.text import MIMEText

subject = 'test mail'
body = 'Hello'
sender = 'personnal.mail@gmail.com'
recipient = 'personnal.mail@gmail.com'
password = "your_gmail_password"


def send_email(subject, body, sender, recipients, password):
    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = recipient 
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp_server:
       smtp_server.login(sender, password)
       smtp_server.sendmail(sender, recipients, msg.as_string())
    print("Message sent!")


send_email(subject, body, sender, recipients, password)

这段代码

with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp_server:
           smtp_server.login(sender, password)
           smtp_server.sendmail(sender, recipients, msg.as_string())

实际上是登录并使用谷歌的SMTP服务器来发送你的邮件。

撰写回答