python将.txt文件发送到邮箱
时间: 2024-02-11 08:04:03 浏览: 221
Ranorex通过Python将报告发送到邮箱的方法
你可以使用Python的SMTP库来发送邮件,具体步骤如下:
1. 导入SMTP库
```python
import smtplib
```
2. 设置SMTP服务器和端口号
```python
smtp_server = 'smtp.邮箱服务商.com' # 邮箱服务商的SMTP服务器地址
smtp_port = 587 # SMTP服务器的端口号
```
3. 登录邮箱账号
```python
sender = '发送者邮箱地址'
password = '发送者邮箱密码'
smtp_obj = smtplib.SMTP(smtp_server, smtp_port)
smtp_obj.starttls() # 开启TLS加密
smtp_obj.login(sender, password)
```
4. 设置邮件内容
```python
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# 创建MIMEMultipart对象
msg = MIMEMultipart()
# 构建邮件正文
body = MIMEText('邮件正文')
msg.attach(body)
# 构建邮件附件
with open('文件路径', 'rb') as f:
attachment = MIMEApplication(f.read(), _subtype='txt')
attachment.add_header('Content-Disposition', 'attachment', filename='文件名.txt')
msg.attach(attachment)
# 设置邮件主题、发件人、收件人
msg['Subject'] = '邮件主题'
msg['From'] = sender
msg['To'] = '接收者邮箱地址'
```
5. 发送邮件
```python
smtp_obj.sendmail(sender, '接收者邮箱地址', msg.as_string())
smtp_obj.quit()
```
完整代码示例:
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
smtp_server = 'smtp.邮箱服务商.com' # 邮箱服务商的SMTP服务器地址
smtp_port = 587 # SMTP服务器的端口号
sender = '发送者邮箱地址'
password = '发送者邮箱密码'
smtp_obj = smtplib.SMTP(smtp_server, smtp_port)
smtp_obj.starttls() # 开启TLS加密
smtp_obj.login(sender, password)
msg = MIMEMultipart()
body = MIMEText('邮件正文')
msg.attach(body)
with open('文件路径', 'rb') as f:
attachment = MIMEApplication(f.read(), _subtype='txt')
attachment.add_header('Content-Disposition', 'attachment', filename='文件名.txt')
msg.attach(attachment)
msg['Subject'] = '邮件主题'
msg['From'] = sender
msg['To'] = '接收者邮箱地址'
smtp_obj.sendmail(sender, '接收者邮箱地址', msg.as_string())
smtp_obj.quit()
```
注意替换代码中的`smtp_server`、`smtp_port`、`sender`、`password`、`文件路径`、`文件名`、`邮件主题`、`邮件正文`、`接收者邮箱地址`等参数为你自己的信息。
阅读全文