I am using the Gmail API, and have strongly followed the example they show in their documentation, which can be found here: https://github.com/googleworkspace/python-samples/blob/main/gmail/snippet/send%20mail/create_draft_with_attachment.py
Thus, I create my email and the attachment as follows:
message = EmailMessage()
message.set_content(email['text'])
message['To'] = email['email']
message['cc'] = "--------@gmail.com"
message['Subject'] = email['subject']
# Attach CV
cv = 'myfile.pdf'
cvtype, _ = mimetypes.guess_type(cv)
cvtypemain, cvtypesub = cvtype.split("/")
cvf = open(cv, "rb")
cv_data = cvf.read()
message.add_attachment(cv_data, cvtypemain, cvtypesub)
# Stuff
encodedmsg = base64.urlsafe_b64encode(message.as_bytes()).decode()
create_draft_request_body = {"message": {"raw": encodedmsg}}
draft = service.users().drafts().create(userId="me", body=create_draft_request_body).execute()
However, this adds the attachment without a name. I strongly suspect this has to do with the build_file_part function in the github snippet above - however, that function is never called in the draft creation part, so I'm not sure what I should be doing with it.
How do I add the attachment properly, using the Gmail APIs and hopefully without a ton of file manipulations? There's bound to be convenience functions for this?
The issue might be that the filename isn't specified when adding the attachment, so Gmail might be defaulting to naming it "noname." If this is the issue you can fix this by explicitly setting the filename when adding the attachment to your EmailMessage. Here's the updated code:
with open(cv, "rb") as cvf:
cv_data = cvf.read()
message.add_attachment(cv_data, maintype=cvtypemain, subtype=cvtypesub, filename='myfile.pdf') # Specify filename here