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. msgHtml: Html message to be sent msgPlain: Alternative plain text message for older email clients
(sender, to, subject, msgHtml, msgPlain, attachmentFile)
| 64 | |
| 65 | |
| 66 | def createMessageWithAttachment(sender, to, subject, msgHtml, msgPlain, attachmentFile): |
| 67 | """Create a message for an email. |
| 68 | |
| 69 | Args: |
| 70 | sender: Email address of the sender. |
| 71 | to: Email address of the receiver. |
| 72 | subject: The subject of the email message. |
| 73 | msgHtml: Html message to be sent |
| 74 | msgPlain: Alternative plain text message for older email clients |
| 75 | attachmentFile: The path to the file to be attached. |
| 76 | |
| 77 | Returns: |
| 78 | An object containing a base64url encoded email object. |
| 79 | """ |
| 80 | message = MIMEMultipart("mixed") |
| 81 | message["to"] = to |
| 82 | message["from"] = sender |
| 83 | message["subject"] = subject |
| 84 | |
| 85 | messageA = MIMEMultipart("alternative") |
| 86 | messageR = MIMEMultipart("related") |
| 87 | |
| 88 | messageR.attach(MIMEText(msgHtml, "html")) |
| 89 | messageA.attach(MIMEText(msgPlain, "plain")) |
| 90 | messageA.attach(messageR) |
| 91 | |
| 92 | message.attach(messageA) |
| 93 | |
| 94 | print("create_message_with_attachment: file:", attachmentFile) |
| 95 | content_type, encoding = mimetypes.guess_type(attachmentFile) |
| 96 | |
| 97 | if content_type is None or encoding is not None: |
| 98 | content_type = "application/octet-stream" |
| 99 | main_type, sub_type = content_type.split("/", 1) |
| 100 | if main_type == "text": |
| 101 | fp = open(attachmentFile, "rb") |
| 102 | msg = MIMEText(fp.read(), _subtype=sub_type) |
| 103 | fp.close() |
| 104 | elif main_type == "image": |
| 105 | fp = open(attachmentFile, "rb") |
| 106 | msg = MIMEImage(fp.read(), _subtype=sub_type) |
| 107 | fp.close() |
| 108 | elif main_type == "audio": |
| 109 | fp = open(attachmentFile, "rb") |
| 110 | msg = MIMEAudio(fp.read(), _subtype=sub_type) |
| 111 | fp.close() |
| 112 | else: |
| 113 | fp = open(attachmentFile, "rb") |
| 114 | msg = MIMEBase(main_type, sub_type) |
| 115 | msg.set_payload(fp.read()) |
| 116 | fp.close() |
| 117 | filename = os.path.basename(attachmentFile) |
| 118 | msg.add_header("Content-Disposition", "attachment", filename=filename) |
| 119 | message.attach(msg) |
| 120 | |
| 121 | return {"raw": base64.urlsafe_b64encode(message.as_string())} |
| 122 | |
| 123 |