python 发送邮件代码
时间: 2023-10-12 15:09:44 浏览: 50
以下是 Python 发送邮件的示例代码:
```python
import smtplib
from email.mime.text import MIMEText
sender_email = 'sender@example.com'
sender_password = 'password'
receiver_email = 'receiver@example.com'
subject = '测试邮件'
msg = MIMEText('这是一封测试邮件。')
msg['Subject'] = subject
msg['From'] = sender_email
msg['To'] = receiver_email
with smtplib.SMTP('smtp.example.com', 587) as smtp:
smtp.starttls()
smtp.login(sender_email, sender_password)
smtp.sendmail(sender_email, receiver_email, msg.as_string())
```
请将 `sender_email` 和 `sender_password` 替换为发送方的电子邮件地址和密码,将 `receiver_email` 替换为接收方的电子邮件地址,并将 `smtp.example.com` 替换为适当的 SMTP 服务器地址。
相关问题
python发送邮件代码 md
以下是一个使用Python发送邮件的示例代码:
```python
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 邮件服务器的地址和端口
smtp_server = 'smtp.example.com'
smtp_port = 25
# 发件人和收件人的邮箱地址
sender = 'sender@example.com'
receiver = 'receiver@example.com'
# 邮件的主题和内容
subject = 'Python邮件示例'
content = '这是一封使用Python发送的邮件。'
# 构造邮件
message = MIMEText(content, 'plain', 'utf-8')
message['From'] = Header(sender, 'utf-8')
message['To'] = Header(receiver, 'utf-8')
message['Subject'] = Header(subject, 'utf-8')
# 发送邮件
try:
smtp_obj = smtplib.SMTP(smtp_server, smtp_port)
smtp_obj.sendmail(sender, receiver, message.as_string())
print("邮件发送成功")
except smtplib.SMTPException as e:
print("邮件发送失败:" + str(e))
```
请注意,你需要将代码中的`smtp_server`、`smtp_port`、`sender`、`receiver`等变量替换为你自己的实际信息。另外,你还需要确保你的计算机可以访问指定的邮件服务器。
python发送邮件最短代码
可以使用Python的smtplib和email库来发送邮件。以下是一个最短的Python发送邮件的示例代码:
``` python
import smtplib
from email.mime.text import MIMEText
msg = MIMEText('邮件正文')
msg['Subject'] = '邮件标题'
msg['From'] = '发件人邮箱'
msg['To'] = '收件人邮箱'
s = smtplib.SMTP('smtp服务器地址')
s.login('发件人邮箱', '邮箱密码')
s.sendmail('发件人邮箱', ['收件人邮箱'], msg.as_string())
s.quit()
```
请注意,需要填写SMTP服务器地址、发件人邮箱、收件人邮箱和邮箱密码等信息才能成功发送邮件。