用python写一段发送邮件的程序
时间: 2023-03-19 14:23:44 浏览: 77
Sure, here's an example Python program that sends an email using the built-in `smtplib` module:
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
# Set up the email parameters
sender = 'your_email_address@example.com'
recipient = 'recipient_email_address@example.com'
subject = 'Subject of your email'
# Create a message container
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = recipient
msg['Subject'] = subject
# Add the message body
body = 'This is the body of your email. You can add HTML content as well.'
msg.attach(MIMEText(body, 'html'))
# Add an image attachment (optional)
with open('path/to/image.png', 'rb') as f:
img_data = f.read()
image = MIMEImage(img_data, name='image.png')
msg.attach(image)
# Connect to the SMTP server and send the email
smtp_server = 'smtp.gmail.com'
smtp_port = 587
smtp_username = 'your_email_address@example.com'
smtp_password = 'your_email_password'
smtp_conn = smtplib.SMTP(smtp_server, smtp_port)
smtp_conn.starttls()
smtp_conn.login(smtp_username, smtp_password)
smtp_conn.sendmail(sender, recipient, msg.as_string())
smtp_conn.quit()
```
In this example, you would need to replace `your_email_address@example.com` with your actual email address and `your_email_password` with your email password. You would also need to replace `recipient_email_address@example.com` with the email address of the recipient you want to send the email to. Finally, if you don't want to include an image attachment, you can remove the code that starts with `with open('path/to/image.png', 'rb')`.
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)