亲爱的Python开发人员,
我一直在尝试编写一个脚本,它将从JSON对象发送一封电子邮件,如下所述。
用例: 该脚本检查Description键的值,并将电子邮件发送到电子邮件地址密钥。它应该在整个JSON中运行并相应地发送电子邮件。
描述值中的内容应包含在邮件正文中。 它应该只在描述开始时发送 “XXX”。如果不是以xxx开头,则不应发送电子邮件。
我遇到迭代问题,因为我只能让它发送一个JSON对象的电子邮件。
我会欣赏新的代码修改。
import json
import urllib.parse
import urllib.request
import json
import sys
import smtplib
from smtplib import SMTPException
#reading the report that has been generated in SolvIT as Json Object
reportJson = [
{
"RequestID":"23"
"Name":"Bob"
"email address":"a@b.com"
"Description":"Please go to point M"
"Position":"Manager"
}
{
"RequestID":"23"
"Name":"Bob"
"email address":"c@g.com"
"Description":"Please go to point 5"
"Position":"Manager"
}
{
"RequestID":"23"
"Name":"Bob"
"email address":"j@v.com"
"Description":"Please go to point 1"
"Position":"Manager"
}
{
"RequestID":"23"
"Name":"Bob"
"email address":"i@c.com"
"Description":"xxxPlease go to point 18"
"Position":"Manager"
}
{
"RequestID":"23"
"Name":"Bob"
"email address":"h@b.com"
"Description":"Please go to point 20"
"Position":"Manager"
}
{
"RequestID":"23"
"Name":"Bob"
"email address":"f@q.com"
"Description":"Please go to point 23"
"Position":"Manager"
}
{
"RequestID":"23"
"Name":"Bob"
"email address":"y@mail.com"
"Description":"xxxPlease go to point 12"
"Position":"Manager"
}
{
"RequestID":"23"
"Name":"Bob"
"email address":"r@mail.com"
"Description":"Please go to point 123"
"Position":"Manager"
}
{
"RequestID":"23"
"Name":"Bob"
"email address":"a@mail.com"
"Description":"xxxPlease go to point 98"
"Position":"Manager"
}
]
#Reading the Request JSON
json_data=open(reportJson).read()
data = json.loads(json_data)
#the 4th row in the report
for dObj in data:
e_mail=dObj['email address']
#the 5th row in the report
for dObj1 in data:
work_log=dObj1['Description']
#if work_log[:2]=:xxx:
# send mail I want to send email only if the description starts
# with xxx, and if it doesn't start with xxx it should send an email
#custom message that is to be sent out
message = """From: Seruken <server2@gmail.com>
MIME-Version: 1.0
Content-type: text/html
Subject: A task in the ticket you created has been resolved
This email sent for the request created with the Subject
""" + " " + work_log
try:
smtpObj = smtplib.SMTP('smtp.gmail.com',587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login('server2@gmail.com', 'password')
smtpObj.sendmail('server2@gmail.com', e_mail, message)
print ("Successfully sent email")
except SMTPException as err:
print ("Error: unable to send email", err)
答案 0 :(得分:0)
# read your report file
with open("report.json") as report_file:
data = json.load(report_file)
for obj in data:
# get description field
description = obj['Description']
# check if it started with 'xxx'
if description.startswith('xxx'):
email = obj['email address']
# send email logic