Gmail和Python,发送不同的电子邮件与相同的附件
问题描述:
我需要发送多封电子邮件(如每天200个定制的电子邮件),但都具有相同的pdf附件。是否有可能只上传附件一次以节省上传时间? 甚至比这更好,是否有可能在谷歌服务器上只上传文件一次,每天只需引用该文件?Gmail和Python,发送不同的电子邮件与相同的附件
只是为了参考这里是代码(修改从谷歌显影剂示例代码位):
# main function
def SendMessageAttachment(sender, to, subject, msgHtml, msgPlain, attachmentFile):
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('gmail', 'v1', http=http)
message1 = create_message_with_attachment(sender, to, subject, msgPlain, attachmentFile)
SendMessageInternal(service, "me", message1)
def SendMessageInternal(service, user_id, message):
try:
message = (service.users().messages().send(userId=user_id, body=message).execute())
print 'Message Id: %s' % message['id']
return message
except errors.HttpError, error:
print 'An error occurred: %s' % error
def create_message_with_attachment(
sender, to, subject, message_text, attachmentFile):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
file: The path to the file to be attached.
Returns:
An object containing a base64url encoded email object.
"""
message = MIMEMultipart()
message['to'] = to
message['from'] = sender
message['subject'] = subject
msg = MIMEText(message_text)
message.attach(msg)
print "create_message_with_attachment: file:", attachmentFile
content_type, encoding = mimetypes.guess_type(attachmentFile)
if content_type is None or encoding is not None:
content_type = 'application/octet-stream'
main_type, sub_type = content_type.split('/', 1)
if main_type == 'text':
fp = open(attachmentFile, 'rb')
msg = MIMEText(fp.read(), _subtype=sub_type)
fp.close()
elif main_type == 'image':
fp = open(attachmentFile, 'rb')
msg = MIMEImage(fp.read(), _subtype=sub_type)
fp.close()
elif main_type == 'audio':
fp = open(attachmentFile, 'rb')
msg = MIMEAudio(fp.read(), _subtype=sub_type)
fp.close()
else:
fp = open(attachmentFile, 'rb')
msg = MIMEBase(main_type, sub_type)
msg.set_payload(fp.read())
fp.close()
filename = os.path.basename(attachmentFile)
msg.add_header('Content-Disposition', 'attachment', filename=filename)
message.attach(msg)
return {'raw': base64.urlsafe_b64encode(message.as_string())}
答
附件被这里加载:
part = MIMEApplication(open("mypdf.pdf","rb").read())
但对于报头可以是参考任何地方
part.add_header('Content-Disposition', 'attachment', filename="file.pdf")
msg.attach(part)
你可以写一个函数来添加这个头之前发送马并遍历所有的收件人。
您可以发送一封包含“BCC”标题中所有收件人的电子邮件吗? – onlynone
@onlynone每封电子邮件都是为收件人定制的(比如他们的名字),所以不可能发送一封邮件。 – apadana