python的selenium自动发送邮件
时间: 2023-07-22 14:52:10 浏览: 168
可以使用selenium和smtplib库来实现Python自动发送邮件功能。具体步骤如下:
1. 导入selenium和smtplib库:
```python
from selenium import webdriver
import smtplib
from email.mime.text import MIMEText
from email.header import Header
```
2. 使用selenium打开邮件网页,输入用户名和密码:
```python
# 使用Chrome浏览器驱动
browser = webdriver.Chrome()
# 打开网页
browser.get('https://mail.qq.com/')
# 输入用户名和密码
username = browser.find_element_by_id('u')
password = browser.find_element_by_id('p')
username.send_keys('your_username')
password.send_keys('your_password')
```
3. 进入写信页面,填写收件人、主题和正文:
```python
# 进入写信页面
compose = browser.find_element_by_id('composebtn')
compose.click()
# 填写收件人、主题和正文
to = browser.find_element_by_name('toarea')
to.send_keys('recipient@example.com')
subject = browser.find_element_by_name('subject')
subject.send_keys('Email Subject')
content = browser.find_element_by_xpath('//*[@id="content"]/div[2]/div[1]/div[2]/iframe')
browser.switch_to.frame(content)
text = browser.find_element_by_xpath('/html/body')
text.send_keys('Email Content')
browser.switch_to.default_content()
```
4. 点击发送按钮:
```python
# 点击发送按钮
send = browser.find_element_by_name('sendbtn')
send.click()
```
5. 使用smtplib库发送邮件:
```python
# 邮件内容
message = MIMEText('Email Content', 'plain', 'utf-8')
message['From'] = Header('Your Name', 'utf-8')
message['To'] = Header('Recipient Name', 'utf-8')
message['Subject'] = Header('Email Subject', 'utf-8')
# 发送邮件
smtpObj = smtplib.SMTP('smtp.example.com', 25)
smtpObj.login('your_username', 'your_password')
smtpObj.sendmail('your_username', ['recipient@example.com'], message.as_string())
smtpObj.quit()
```
注意:需要将以上代码中的`your_username`、`your_password`和`recipient@example.com`替换为实际的值。另外,smtplib库需要根据邮件服务器的配置进行相应的修改。
阅读全文