我想从excel文件中提取标记,名称和卷号,并通过电子邮件发送到学生的电子邮件中,该电子邮件也在excel文件中。每行包含不同学生的详细信息及其电子邮件。我想在每行的电子邮件中邮寄他们的详细信息。下面的代码不会发送任何电子邮件。发送电子邮件需要做什么?我正在运行python 3.6。
不同excel文件的图像 这是我正在尝试运行的python代码
import smtplib
from email.mime.multipart import MIMEMultipart
from openpyxl import load_workbook
gmail_user = "username@gmail.com"
gmail_appPassword = "password"
msg = MIMEMultipart('alternative')
sent_from = ['username@gmail.com']
msg['Subject'] = 'Marksheet'
#excel-file=data
def list_marks():
excelfile = 'simple_excelmail.xlsx'
wb = load_workbook(excelfile)
ws = wb[wb.sheetnames[0]]
excel_list = []
for row in ws.iter_rows(row_offset=1):
for cell in row:
# print(cell.value)
excel_list.append(str(cell.value))
return excel_list
# Marks is Constructor. Builds template rows for html
class Marks:
def __init__(self, name, roll_num, maths, physics, chemistry, english, computer_sci, result):
self.name = name
self.roll_num = roll_num
self.maths = maths
self.physics = physics
self.chemistry = chemistry
self.english = english
self.computer_sci = computer_sci
self.result = result
self.total = 0
self.template_array = []
# sum amounts for total
for i in range(0, len(self.roll_num)):
self.total += int(self.maths[i]+self.physics[i]+self.chemistry[i]+self.english[i]+self.computer_sci[i])
template = """
<tr class="left">
<td style="padding: 10px; text-align: left;">"""+ self.roll_num[i] +"""</td>
<td style="padding: 10px;">""" + self.maths[i] + """</td>
<td style="text-align: right; padding: 10px;">"""+ self.physics[i] +"""</td>
<td style="padding-left: 20px;">"""+ self.chemistry[i] +"""</td>
<td style="padding-left: 20px;">"""+ self.english[i] +"""</td>
<td style="padding-left: 20px;">"""+ self.computer_sci[i] +"""</td>
<td style="padding-left: 20px;">"""+ self.total[i] +"""</td>
<td style="padding-left: 20px;">"""+ self.result[i] +"""</td>
</tr>
"""
self.template_array.append(template)
self.total = str(self.total)
def send_email(to, msg, new_template):
data.reverse()
for i in range(0, 9):
data.pop()
try:
data.reverse()
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.login(gmail_user, gmail_pword)
server.sendmail(sent_from, to, msg.as_string())
print("Email Sent To: ", new_template.name)
print("@: ", to)
print("Roll Number: ", new_template.roll_num)
print("TOTAL: ", new_template.total, "---------------------------")
server.quit()
if(data[0] == 'None'):
print('END OF LIST')
else:
build_email(data)
except Exception as e:
print(e)
print('Email Failed to Send to: ', new_template.name)
print("@: ", to)
print("Roll Numbers: ", new_template.roll_num)
data = list_marks()
def build_email(data):
new_template = Marks(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7])
to = data[8].split(",") #List of emails
text = "Hello, {0}, \n Please find the following marks attached {1} on these roll numbers for the following students.\n Thank You.\n ".format(data[0], data[1])
html = """\
<!DOCTYPE html>
<html>
<body>
<p style="text-align: center"> Hello, """+ new_template.name +""" Hope this email finds you well.</p>
<p style="text-align: center">Here are your marks</p>
<hr style="width: 500px;">
<table style="margin-left: auto; margin-right: auto">
<tr>
<th>Marks TOTAL:</th>
<th style="padding-left: 100px">$"""+ new_template.total +"""</th>
</tr>
</table>
<hr class="width">
<table style="margin-left: auto; margin-right: auto">
<tr class="left padded">
<th style="text-align: left;"> Roll Number </th>
<th> Maths </th>
<th style="text-align: right;"> Physics </th>
<th style="padding-left: 20px;"> Chemistry</th>
<th style="padding-left: 20px;"> English</th>
<th style="padding-left: 20px;"> Computer Science</th>
<th style="padding-left: 20px;"> Result</th>
</tr>
""" + ''.join(new_template.template_array) + """
</table>
<hr style="width: 500px;">
<table style="margin-left: auto; margin-right: auto; padding: 10px;">
<tr>
<th> Thank You! </th>
</tr>
<tr>
<th> Any School </th>
</tr>
</table>
<hr style="width: 500px;">
</body>
</html>
"""
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
msg.attach(part1)
msg.attach(part2)
send_email(to, msg, new_template)
build_email(data)
答案 0 :(得分:0)
建议您不要使用Python,而要使用Excel和Outlook来完成这项工作。这是一些VBA代码,应该(几乎)执行您想要的操作。您可能需要稍微修改代码以符合您的特定设置。
In column A : Names of the people
In column B : E-mail addresses
In column C:Z : Filenames like this C:\Data\Book2.xls (don't have to be Excel files)
宏将循环遍历“ Sheet1”中的每一行,并且如果B列中有电子邮件地址 和C:Z列中的文件名,它将创建包含此信息的邮件并发送。
Sub Send_Files()
'Working in Excel 2000-2016
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
Dim OutApp As Object
Dim OutMail As Object
Dim sh As Worksheet
Dim cell As Range
Dim FileCell As Range
Dim rng As Range
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set sh = Sheets("Sheet1")
Set OutApp = CreateObject("Outlook.Application")
For Each cell In sh.Columns("B").Cells.SpecialCells(xlCellTypeConstants)
'Enter the path/file names in the C:Z column in each row
Set rng = sh.Cells(cell.Row, 1).Range("C1:Z1")
If cell.Value Like "?*@?*.?*" And _
Application.WorksheetFunction.CountA(rng) > 0 Then
Set OutMail = OutApp.CreateItem(0)
With OutMail
.to = cell.Value
.Subject = "Testfile"
.Body = "Hi " & cell.Offset(0, -1).Value
For Each FileCell In rng.SpecialCells(xlCellTypeConstants)
If Trim(FileCell) <> "" Then
If Dir(FileCell.Value) <> "" Then
.Attachments.Add FileCell.Value
End If
End If
Next FileCell
.Send 'Or use .Display
End With
Set OutMail = Nothing
End If
Next cell
Set OutApp = Nothing
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub