python爬取公告通知发送邮件
时间: 2023-09-25 20:15:57 浏览: 53
你可以使用Python中的requests库来爬取公告通知的内容,然后使用smtplib库来发送邮件。下面是一个简单的示例代码:
```python
import requests
import smtplib
from email.mime.text import MIMEText
def send_mail(subject, body):
# 设置发件人和收件人
sender = 'your_email@example.com'
receiver = 'recipient_email@example.com'
# 设置SMTP服务器地址和端口号
smtp_server = 'smtp.example.com'
smtp_port = 587
# 设置发件人邮箱的用户名和密码
username = 'your_email@example.com'
password = 'your_password'
# 创建邮件内容
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receiver
try:
# 连接SMTP服务器并登录
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
# 发送邮件
server.sendmail(sender, receiver, msg.as_string())
print('邮件发送成功')
except Exception as e:
print('邮件发送失败:', str(e))
finally:
# 关闭连接
server.quit()
def crawl_announcement(url):
try:
# 发起HTTP请求并获取页面内容
response = requests.get(url)
if response.status_code == 200:
# 解析页面内容并提取公告通知
announcements = response.json() # 假设返回的是JSON格式数据,具体根据实际情况修改解析方式
return announcements
else:
print('请求失败,状态码:', response.status_code)
except Exception as e:
print('请求出错:', str(e))
# 爬取公告通知
announcements = crawl_announcement('http://example.com/announcements')
if announcements:
# 构造邮件内容
subject = '最新公告通知'
body = '\n'.join(announcements)
# 发送邮件
send_mail(subject, body)
```
以上代码中,`crawl_announcement`函数用于爬取公告通知的内容,`send_mail`函数用于发送邮件。你需要根据实际情况修改URL、发件人和收件人的邮箱地址,SMTP服务器的地址和端口号,以及发件人邮箱的用户名和密码。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)