Отправляйте автоматические электронные письма от python в зависимости от условий прикрепления файлов - PullRequest
0 голосов
/ 17 июня 2020

Я пытаюсь отправить автоматическое электронное письмо, используя python. Я хочу изменить код на основе некоторого условия.

1) Если вложение не пустое, тогда получатель и содержимое почты должны быть такими, как показано ниже

receiver_address = 'abc@gmail.com'
cc_address="efg@gmail.com'
mail_content = ''' PFA the lastest file '''

2) иначе это должно быть

receiver_address = 'xyz@gmail.com'
cc_address="efg@gmail.com'
mail_content = ''' File is empty '''

Мой код

data1.to_excel('Report.xlsx')
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from datetime import date

mail_content = '''PFA the latest file'''
sender_address = 'will@gmail.com'
receiver_address = 'abc@gmail.com'
#Setup the MIME
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = "Weekly Active Billing Report for week ending on" +" " + (ls).strftime('%Y%m%d')

#The subject line
#The body and the attachments for the mail
message.attach(MIMEText(mail_content, 'plain'))
attach_file_name = 'Report.xlsx'
attach_file = open(attach_file_name, 'rb') # Open the file as binary mode
payload = MIMEBase('application', 'octate-stream')
payload.set_payload((attach_file).read())
encoders.encode_base64(payload) #encode the attachment
#add payload header with filename
#payload.add_header('Content-Decomposition', 'attachment', filename=attach_file_name)
payload.add_header('Content-Disposition',"attachment; filename=%s" % attach_file_name)
message.attach(payload)

#Create SMTP session for sending the mail
session = smtplib.SMTP('smtplocal.xx.xx.xx',25) #use gmail with port
#session.starttls() #enable security
#session.login(sender_address, sender_pass) #login with mail_id and password
text = message.as_string()
session.sendmail(sender_address, receiver_address.split(",") , text) 
session.quit()
print('Mail Sent')

1 Ответ

1 голос
/ 17 июня 2020

Используйте словарь, чтобы получить требуемые значения в зависимости от того, пуст файл или нет, и обновите переменные. Это должно сработать.

data1.to_excel('Report.xlsx')
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from datetime import date

import os

attach_file_name = 'Report.xlsx'
filesize = os.stat(attach_file_name).st_size
dict1 = {"Non-empty": { 'receiver': 'xyz@gmail.com', "mail_content": " PFA the lastest file" } ,
        "Empty": { "receiver": 'abc@gmail.com',  "mail_content":" File is empty " }}
receiver_address = ""
mail_content = ""
if filesize == 0:
    receiver_address = dict1["Empty"]["receiver"]
    mail_content = dict1["Empty"]["mail_content"]
else:
    receiver_address = dict1["Non-empty"]["receiver"]
    mail_content = dict1["Non-empty"]["mail_content"]


mail_content = '''PFA the latest file'''
sender_address = 'will@gmail.com'
#Setup the MIME
message = MIMEMultipart()

# Rest of the code is same. 
...