python 发送邮件代码
时间: 2023-10-12 17:09:44 浏览: 95
以下是 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发送邮件代码报错:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb9 in position 0: invalid start byte
在Python发送邮件时出现UnicodeDecodeError错误通常是因为邮件内容中包含了无法使用UTF-8编码解码的字符。解决这个问题的方法是使用正确的编码格式来解码邮件内容。
以下是一个示例代码,演示了如何发送邮件并处理UnicodeDecodeError错误:
```python
import smtplib
from email.mime.text import MIMEText
def send_email():
# 邮件内容
content = "邮件内容"
# 创建MIMEText对象,指定邮件内容和编码格式
msg = MIMEText(content, 'plain', 'utf-8')
# 设置发件人和收件人
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
# 发送邮件
try:
smtp = smtplib.SMTP('smtp.example.com')
smtp.send_message(msg)
smtp.quit()
print("邮件发送成功")
except UnicodeDecodeError:
# 如果出现UnicodeDecodeError错误,尝试使用其他编码格式解码邮件内容
msg.set_charset('gbk') # 使用GBK编码解码邮件内容
smtp = smtplib.SMTP('smtp.example.com')
smtp.send_message(msg)
smtp.quit()
print("邮件发送成功")
send_email()
```
在上述代码中,我们首先创建了一个MIMEText对象,并指定了邮件内容和编码格式为UTF-8。然后,我们尝试发送邮件,如果出现UnicodeDecodeError错误,我们将重新设置编码格式为GBK,并再次发送邮件。
阅读全文
相关推荐









