未收到 SMTPlib 附件
SMTPlib Attachments not received
我一直在使用基于 http://datamakessense.com/easy-scheduled-emailing-with-python-for-typical-bi-needs/ 中的代码片段的代码,通过我公司的电子邮件向客户发送 PDF 附件。我们一次通过一个电子邮件地址 ("no-reply@companyname.com") 发送大约 100 封这样的电子邮件,并且对于发送的每封电子邮件,我也会将密件抄送副本发送到一个内部电子邮件地址 ("reports@companyname.com")。
有时(大约 100 人中有 5 人),客户报告没有收到附件。有时根本不显示,有时显示时带有红色问号。但是,BCC 副本总是有附件,没有问题,进入发送帐户,电子邮件的发送副本总是显示附件,也没有问题。没有收到附件的客户邮件没有明显的相似之处(比如共享域;实际上大部分都是@gmail.com)。没有要报告的异常或错误。一切看起来都在正常工作。
这是我第一次使用 MIME 或通过 Python 自动发送电子邮件,但它 98% 的时间都在工作,这让我感到困惑。是否有可能发生这种情况的已知原因?也许我没有正确设置类型?或者我应该为 Gmail 使用 MIME 做些什么?
这是我的代码:
wdir = 'PDFs\'
filelist = []
for file in os.listdir(wdir):
if file.endswith('.pdf'):
filelist += [wdir + file] # sending all of the PDFs in a local directory
email = {}
rf = wdir + 'Reports_data.csv' # get email addresses for customers by ID (row[2])
with open(rf, 'rbU') as inf:
read = csv.reader(inf)
read.next()
for row in read:
email[row[2]] = row[3]
hfi = open('HTML\email.html', 'rb') # the HTML for the email body, itself
htmltxt = hfi.read()
hfi.close()
class Bimail:
def __init__(self, subject, recipients):
self.subject = subject
self.recipients = recipients
self.htmlbody = ''
self.sender = "foo@bar.com"
self.senderpass = 'password'
self.attachments = []
def send(self):
msg = MIMEMultipart('alternative')
msg['From'] = self.sender
msg['Subject'] = self.subject
msg['To'] = self.recipients[0]
msg.preamble = "preamble goes here"
if self.attachments:
self.attach(msg)
msg.attach(MIMEText(self.htmlbody, 'html'))
s = smtplib.SMTP('smtp.gmail.com:587')
s.starttls()
s.login(self.sender, self.senderpass)
s.sendmail(self.sender, self.recipients, msg.as_string())
s.quit()
def htmladd(self, html):
self.htmlbody = self.htmlbody + '<p></p>' + html
def attach(self, msg):
for f in self.attachments:
ctype, encoding = mimetypes.guess_type(f)
if ctype is None or encoding is not None:
ctype = "application/octet-stream"
maintype, subtype = ctype.split("/", 1)
fn = f.replace(wdir, '')
fp = open(f, "rb")
attachment = MIMEBase(maintype, subtype)
attachment.set_payload(fp.read())
fp.close()
encoders.encode_base64(attachment)
attachment.add_header("Content-Disposition", "attachment", filename=fn)
attachment.add_header('Content-ID', '<{}>'.format(f)) # or should this be format(fn)?
msg.attach(attachment)
def addattach(self, files):
self.attachments = self.attachments + files
if __name__ == '__main__':
for fi in filelist:
code = fi.split('_')[1].split('\')[1] # that "ID" for email is in the filename
addr = email[code]
mymail = Bimail(('SUBJECT HERE'), [addr, 'reports@ourcompany.com'])
mymail.htmladd(htmltxt)
mymail.addattach([fi])
mymail.send()
试试这个代码块:
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
fromaddr = "from@yourcompany.com"
password = "password"
toaddr = "to@yourcompany.com"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Report"
body = "Hi, have a look at the Report"
msg.attach(MIMEText(body, 'plain'))
filename = "Report.pdf"
attachment = open("Report.pdf", "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP('smtp.office365.com', 587)
server.starttls()
server.login(fromaddr, "password")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
对我有用
每封电子邮件发送近 100 个附件并不是每个人每天都习惯做的事情,您是否检查过 google SMTP 服务器端没有限制?
以下问题与 "Gmail sending limits in G Suite" 有关,但在我看来,类似的规则适用于任何其他 gmail 帐户。
https://support.google.com/a/answer/2956491#sendinglimitsforrelay
https://support.google.com/a/answer/166852?hl=en
请看下面我的发送邮件功能:
def sendMail(to, subject, text, files=[],server="smtp.gmail.com:587",username="contact.name",password="mygmailurrentpassord"):
assert type(to)==list
assert type(files)==list
fro = "Contact Name <contact.name@gmail.com>"
msg = MIMEMultipart()
msg['From'] = fro
msg['To'] = COMMASPACE.join(to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach( MIMEText(text) )
for file in files:
part = MIMEBase('application', "octet-stream")
part.set_payload( open(file,"rb").read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"'
% os.path.basename(file))
msg.attach(part)
smtp = smtplib.SMTP(server)
smtp.starttls()
smtp.login(username,password)
smtp.sendmail(fro, to, msg.as_string() )
smtp.close()
此致
我一直在使用基于 http://datamakessense.com/easy-scheduled-emailing-with-python-for-typical-bi-needs/ 中的代码片段的代码,通过我公司的电子邮件向客户发送 PDF 附件。我们一次通过一个电子邮件地址 ("no-reply@companyname.com") 发送大约 100 封这样的电子邮件,并且对于发送的每封电子邮件,我也会将密件抄送副本发送到一个内部电子邮件地址 ("reports@companyname.com")。
有时(大约 100 人中有 5 人),客户报告没有收到附件。有时根本不显示,有时显示时带有红色问号。但是,BCC 副本总是有附件,没有问题,进入发送帐户,电子邮件的发送副本总是显示附件,也没有问题。没有收到附件的客户邮件没有明显的相似之处(比如共享域;实际上大部分都是@gmail.com)。没有要报告的异常或错误。一切看起来都在正常工作。
这是我第一次使用 MIME 或通过 Python 自动发送电子邮件,但它 98% 的时间都在工作,这让我感到困惑。是否有可能发生这种情况的已知原因?也许我没有正确设置类型?或者我应该为 Gmail 使用 MIME 做些什么?
这是我的代码:
wdir = 'PDFs\'
filelist = []
for file in os.listdir(wdir):
if file.endswith('.pdf'):
filelist += [wdir + file] # sending all of the PDFs in a local directory
email = {}
rf = wdir + 'Reports_data.csv' # get email addresses for customers by ID (row[2])
with open(rf, 'rbU') as inf:
read = csv.reader(inf)
read.next()
for row in read:
email[row[2]] = row[3]
hfi = open('HTML\email.html', 'rb') # the HTML for the email body, itself
htmltxt = hfi.read()
hfi.close()
class Bimail:
def __init__(self, subject, recipients):
self.subject = subject
self.recipients = recipients
self.htmlbody = ''
self.sender = "foo@bar.com"
self.senderpass = 'password'
self.attachments = []
def send(self):
msg = MIMEMultipart('alternative')
msg['From'] = self.sender
msg['Subject'] = self.subject
msg['To'] = self.recipients[0]
msg.preamble = "preamble goes here"
if self.attachments:
self.attach(msg)
msg.attach(MIMEText(self.htmlbody, 'html'))
s = smtplib.SMTP('smtp.gmail.com:587')
s.starttls()
s.login(self.sender, self.senderpass)
s.sendmail(self.sender, self.recipients, msg.as_string())
s.quit()
def htmladd(self, html):
self.htmlbody = self.htmlbody + '<p></p>' + html
def attach(self, msg):
for f in self.attachments:
ctype, encoding = mimetypes.guess_type(f)
if ctype is None or encoding is not None:
ctype = "application/octet-stream"
maintype, subtype = ctype.split("/", 1)
fn = f.replace(wdir, '')
fp = open(f, "rb")
attachment = MIMEBase(maintype, subtype)
attachment.set_payload(fp.read())
fp.close()
encoders.encode_base64(attachment)
attachment.add_header("Content-Disposition", "attachment", filename=fn)
attachment.add_header('Content-ID', '<{}>'.format(f)) # or should this be format(fn)?
msg.attach(attachment)
def addattach(self, files):
self.attachments = self.attachments + files
if __name__ == '__main__':
for fi in filelist:
code = fi.split('_')[1].split('\')[1] # that "ID" for email is in the filename
addr = email[code]
mymail = Bimail(('SUBJECT HERE'), [addr, 'reports@ourcompany.com'])
mymail.htmladd(htmltxt)
mymail.addattach([fi])
mymail.send()
试试这个代码块:
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
fromaddr = "from@yourcompany.com"
password = "password"
toaddr = "to@yourcompany.com"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Report"
body = "Hi, have a look at the Report"
msg.attach(MIMEText(body, 'plain'))
filename = "Report.pdf"
attachment = open("Report.pdf", "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP('smtp.office365.com', 587)
server.starttls()
server.login(fromaddr, "password")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
对我有用
每封电子邮件发送近 100 个附件并不是每个人每天都习惯做的事情,您是否检查过 google SMTP 服务器端没有限制?
以下问题与 "Gmail sending limits in G Suite" 有关,但在我看来,类似的规则适用于任何其他 gmail 帐户。
https://support.google.com/a/answer/2956491#sendinglimitsforrelay
https://support.google.com/a/answer/166852?hl=en
请看下面我的发送邮件功能:
def sendMail(to, subject, text, files=[],server="smtp.gmail.com:587",username="contact.name",password="mygmailurrentpassord"):
assert type(to)==list
assert type(files)==list
fro = "Contact Name <contact.name@gmail.com>"
msg = MIMEMultipart()
msg['From'] = fro
msg['To'] = COMMASPACE.join(to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach( MIMEText(text) )
for file in files:
part = MIMEBase('application', "octet-stream")
part.set_payload( open(file,"rb").read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"'
% os.path.basename(file))
msg.attach(part)
smtp = smtplib.SMTP(server)
smtp.starttls()
smtp.login(username,password)
smtp.sendmail(fro, to, msg.as_string() )
smtp.close()
此致