我一直在使用基于http://datamakessense.com/easy-scheduled-emailing-with-python-for-typical-bi-needs/代码段的代码,通过我公司的电子邮件向客户发送PDF附件。我们通过一个电子邮件地址(" no-reply@companyname.com")一次发送大约100个,并且对于发送的每封电子邮件,我将BCC副本发送到内部电子邮件地址,如好(" reports@companyname.com")。
不时(约100个中的5个),客户报告没有获得附件。有时它根本没有显示,有时它会显示一个红色问号。但是,BCC副本始终没有任何问题的附件,并且进入发送帐户,发送的电子邮件副本始终显示附件,也没有问题。客户中没有明显的相似之处。没有收到附件的电子邮件(例如共享域名;实际上,大多数是@ gmail.com)。报告没有例外或错误。一切看起来都好像正常工作。
这是我第一次使用MIME或通过Python自动化电子邮件,但它在98%的时间工作这一事实令我感到困惑。是否有可能发生这种情况的原因?也许我没有正确设置类型?或者我应该使用MIME for Gmail做些什么特别的事情?
这是我的代码:
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()
答案 0 :(得分:2)
试试这段代码:
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()
它对我有用
答案 1 :(得分:2)
每封电子邮件发送近100个附件不是每个人每天都习惯做的事情,你检查谷歌SMTP服务器端没有限制吗?
以下问题与G Suite&#34;中的Gmail发送限制有关,但在我看来,其他任何gmail帐户都有类似的规则。
https://support.google.com/a/answer/2956491#sendinglimitsforrelay
https://support.google.com/a/answer/166852?hl=en
请参阅我的sendmail函数:
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()
此致