python 发送邮件代码
时间: 2023-10-12 19:09:44 浏览: 90
以下是 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发送邮件代码
在Python中,你可以使用内置的`smtplib`和`email`库来发送电子邮件。以下是一个基本的示例,展示了如何使用这两个模块创建并发送一封简单的邮件:
```python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# 邮件配置
sender_email = 'your-email@example.com'
receiver_email = 'recipient-email@example.com'
password = 'your-password'
smtp_server = 'smtp.example.com' # 根据你的SMTP服务器填写
subject = 'Hello from Python'
body = 'This is a test email sent using Python.'
# 创建邮件对象
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject
# 添加邮件正文
msg.attach(MIMEText(body, 'plain'))
try:
# 连接SMTP服务器
server = smtplib.SMTP(smtp_server, 587)
server.starttls() # 加密连接
# 登录邮箱
server.login(sender_email, password)
# 发送邮件
server.sendmail(sender_email, receiver_email, msg.as_string())
print(f"Email sent successfully to {receiver_email}.")
except Exception as e:
print(f"Error sending email: {e}")
finally:
# 关闭连接
server.quit()
```
记得替换上述代码中的`your-email@example.com`、`recipient-email@example.com`、`your-password`和`smtp.example.com`为你自己的信息。
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`等变量替换为你自己的实际信息。另外,你还需要确保你的计算机可以访问指定的邮件服务器。
阅读全文