发送Python smtplib之前检查电子邮件的完整大小

问题描述

我无法使用Python通过smtplib通过电子邮件发送文件。

我在Kubernetes Cluster-Jupyter Notebook上运行代码。

我收到错误SMTPSenderRefused:

SMTPSenderRefused                         Traceback (most recent call last)
<ipython-input-72-9046ec8e66c3> in <module>
      1 # Send message
----> 2 s.send_message(msg)
      3 

/opt/app-root/conda/lib/python3.7/smtplib.py in send_message(self,msg,from_addr,to_addrs,mail_options,rcpt_options)
    965             flatmsg = bytesmsg.getvalue()
    966         return self.sendmail(from_addr,flatmsg,--> 967                              rcpt_options)
    968 
    969     def close(self):

/opt/app-root/conda/lib/python3.7/smtplib.py in sendmail(self,rcpt_options)
    865             else:
    866                 self._rset()
--> 867             raise SMTPSenderRefused(code,resp,from_addr)
    868         senderrs = {}
    869         if isinstance(to_addrs,str):

SMTPSenderRefused: (552,b'size limit exceeded',

这是一个gzip文件,重约15mb。我检查了可以发送的最大大小:

smtp = smtplib.SMTP('mailhub.company.com') 
smtp.ehlo()   
max_limit_in_bytes = int( smtp.esmtp_features['size'] )
max_limit_in_bytes

得到了20971520,大约21mb。

所以我的问题是:

在发送之前如何获得整个电子邮件的确切大小(附件+包装纸等)?

是否有一种方法可以尽可能限制电子邮件的大小,以便为文件留出更多空间?

我尝试直接通过Outlook发送相同的文件和电子邮件正文,但没有任何问题。这仅在我尝试使用Python时发生。

这是我的电子邮件发件人功能:

def emailer():
# instance of MIMEMultipart
msg = MIMEMultipart()

# Text message to be sent in the body of the mail
text = """\
Report delivery #12345

"""
# attach the message body with the msg instance
msg.attach(MIMEText(text,'plain'))

# File to be sent
data_out = !pwd
db_file = 'TEST_2020-10-20.csv.gz'
fileAbsolutePath = data_out[0]+'/'+db_file
attachment = open(fileAbsolutePath,"rb")

# instance of MIMEBase and named as p
p = MIMEBase('application','octet-stream')

# To change the payload into encoded form
p.set_payload((attachment).read())

# encode into base64
encoders.encode_base64(p)

p.add_header('Content-Disposition',"attachment; filename= %s" % filename)

# Attach the file to be emailed
msg.attach(p)

msg['Subject'] = f'Report #12345'
msg['From'] = "[email protected]"
msg['To'] = "[email protected]"

# Connect to the SMTP server.
s = smtplib.SMTP('mailhub.company.com',25)

# start TLS for security
s.starttls()

# Send message
s.send_message(msg)

# terminating the session
s.quit()

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)