Python 发送 OutLook邮件

# Python 发送 OutLook邮件

## 直接执行发送邮件

“`python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

# 发件人邮箱账号和授权码(若开启了两步验证,使用应用专用密码)
sender_email = “17600000142@163.com”
sender_password = “123123123”

# 收件人邮箱
receiver_email = “17600000142@163.com”

# 邮件主题和正文
body = f”””

服务名称 服务状态
MasterServer 正常

“””
subject = f”{‘red’ not in body and ‘正常’ or ‘异常’}!!服务状态监控”

# 附件集合,可根据实际情况修改
attachments = None

# 创建一个 MIMEMultipart 对象,用于表示邮件内容
msg = MIMEMultipart()
msg[‘From’] = sender_email
msg[‘To’] = receiver_email
msg[‘Subject’] = subject

# 添加邮件正文
msg.attach(MIMEText(body, ‘html’, ‘utf-8’))

# 检查是否有附件
if attachments:
for attachment_path in attachments:
try:
with open(attachment_path, “rb”) as file:
part = MIMEApplication(file.read(), Name=attachment_path.split(“/”)[-1])
part[‘Content-Disposition’] = f’attachment; filename=”{attachment_path.split(“/”)[-1]}”‘
msg.attach(part)
except FileNotFoundError:
print(f”附件 {attachment_path} 未找到,将忽略该附件。”)

try:
# 创建 SMTP 对象并连接到 Outlook 的 SMTP 服务器
server = smtplib.SMTP(“smtp.outlook.com”, 587)
# 启用 TLS 加密
server.starttls()
# 登录发件人邮箱
server.login(sender_email, sender_password)
# 发送邮件
server.sendmail(sender_email, [receiver_email], msg.as_string())
print(“邮件发送成功!”)
except Exception as e:
print(f”邮件发送失败:{e}”)
finally:
if ‘server’ in locals() and server:
# 关闭 SMTP 连接
server.quit()
“`

## 邮件发送服务,单独运行

“`python
import json
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

from flask import Flask, request, jsonify, Response
app = Flask(__name__)

def send_email(smtp_server, smtp_port, email_name, password, recipient_email, subject, content, attachments=None):
# 设置邮件内容
recipient_list = recipient_email.split(‘|’) # 将多个收件人地址拆分为列表
recipient_list = [email.strip() for email in recipient_list] # 去除可能的空格
recipient_str = “, “.join(recipient_list) # 用于显示在邮件头中

# 创建一个 MIMEMultipart 对象,用于表示邮件内容
msg = MIMEMultipart()
msg[‘From’] = email_name
msg[‘To’] = recipient_str
msg[‘Subject’] = subject

# 添加邮件正文
msg.attach(MIMEText(content, ‘html’, ‘utf-8’))

# 检查是否有附件
if attachments:
for attachment_path in attachments:
try:
with open(attachment_path, “rb”) as file:
part = MIMEApplication(file.read(), Name=attachment_path.split(“/”)[-1])
part[‘Content-Disposition’] = f’attachment; filename=”{attachment_path.split(“/”)[-1]}”‘
msg.attach(part)
except FileNotFoundError:
print(f”附件 {attachment_path} 未找到,将忽略该附件。”)

try:
# 创建 SMTP 对象并连接到 Outlook 的 SMTP 服务器
server = smtplib.SMTP(smtp_server, smtp_port)
# 启用 TLS 加密
server.starttls()
# 登录发件人邮箱
server.login(email_name, password)
# 发送邮件
server.sendmail(email_name, recipient_list, msg.as_string())
print(“邮件发送成功!”)
server.quit() # 退出SMTP连接
return True
except Exception as e:
print(f”邮件发送失败:{e}”)
return False

@app.route(‘/send_email’, methods=[‘POST’])
def send_email_api():
# 获取请求中的参数
smtp_server = request.json.get(‘smtp_server’)
smtp_port = request.json.get(‘smtp_port’)
email_name = request.json.get(’email_name’)
password = request.json.get(‘password’)
recipient_email = request.json.get(‘recipient_email’)
subject = request.json.get(‘subject’)
content = request.json.get(‘content’)

print(smtp_server, smtp_port, email_name, password, recipient_email, subject, content)

if not subject or not content:
# 返回错误消息
return Response(
json.dumps({‘status’: ‘error’, ‘message’: ‘主题与内容均为必填项,不能为空!’}, ensure_ascii=False),
mimetype=’application/json’), 400

# 调用发送邮件的方法
if send_email(smtp_server, smtp_port, email_name, password, recipient_email, subject, content):
# 返回成功消息
return Response(json.dumps({‘status’: ‘success’, ‘message’: ‘发送邮件成功!’}, ensure_ascii=False),
mimetype=’application/json’), 200
else:
# 返回失败消息
return Response(json.dumps({‘status’: ‘error’, ‘message’: ‘发送邮件失败!’}, ensure_ascii=False),
mimetype=’application/json’), 500

# 发送邮件接口(带附件)
@app.route(‘/send_email_file’, methods=[‘POST’])
def send_email_file():
# 获取请求中的参数
smtp_server = request.form.get(‘smtp_server’)
smtp_port = request.form.get(‘smtp_port’)
email_name = request.form.get(’email_name’)
password = request.form.get(‘password’)
recipient_email = request.form.get(‘recipient_email’)
subject = request.form.get(‘subject’)
content = request.form.get(‘content’)

# 获取上传的文件(附件)
files = request.files.getlist(‘attachments’)

if not subject or not content:
# 返回错误消息
return Response(
json.dumps({‘status’: ‘error’, ‘message’: ‘主题与内容均为必填项,不能为空!’}, ensure_ascii=False),
mimetype=’application/json’), 400

# 调用发送邮件的方法,传入附件
if send_email(smtp_server, smtp_port, email_name, password, recipient_email, subject, content, attachments=files):
# 返回成功消息
return Response(json.dumps({‘status’: ‘success’, ‘message’: ‘发送邮件成功!’}, ensure_ascii=False),
mimetype=’application/json’), 200
else:
# 返回失败消息
return Response(json.dumps({‘status’: ‘error’, ‘message’: ‘发送邮件失败!’}, ensure_ascii=False),
mimetype=’application/json’), 500

if __name__ == ‘__main__’:
app.run(debug=True, host=’0.0.0.0′, port=5870)

“`

### 请求示例

**调用发送邮件接口时需要将逗号换成|**

“`python
from datetime import datetime
import requests

# 发送邮件
def send_mail(subject, content):
“””
发送邮件
:param subject: 邮件主题
:param content: 邮件内容
:return: {
“status”: “success”,
“message”: “发送邮件成功!”
}

“””
# 收件人
recipient_email = “9123949@qq.com,17600000142@163.com”
mail_server = “http://127.0.0.1:5870/”
mail_response = requests.post(f'{mail_server}/send_email’, json={
“smtp_server”: “smtp.outlook.com”,
“smtp_port”: 587,
“email_name”: “17600000142@163.com”,
“password”: “123123123123”,
“recipient_email”: recipient_email.replace(“,”, “|”),
“subject”: subject,
“content”: content
}).json()
if mail_response.get(“status”) == “success”:
print(“成功”)
return True
print(“失败”)
return False

if __name__ == ‘__main__’:
now_date = datetime.now().strftime(“%Y-%m-%d %H:%M:%S”)
print(f”开始检查服务器状态——> {now_date}”)
html = f”””

服务名称 服务状态
MasterServer 正常

“””
send_mail(f”{‘red’ not in html and ‘正常’ or ‘异常’}!!TD服务状态监控:{now_date}”, html)
“`

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇