def _construct_message_root(has_attachments: bool, contains_html: bool) -> message.Message: if has_attachments: return MIMEMultipart("related") elif contains_html: return MIMEMultipart("alternative") else: return message.Message()
def get_msg_body(self, msg_id): """Get the plain text portion of the given message's body. Args: msg_id: The id of the message, which can be used to get details of the message. Returns: The plaintext message body if it exists. Otherwise, None. """ # Get message message = read_email.GetMimeMessage(self.service, msg_id) # Find the plain text part of the message body plain_txt_msg = email_msg.Message() if not message.is_multipart() and \ (message.get_content_type() == 'text/plain'): plain_txt_msg = message elif message.is_multipart(): # Go through message and capture plain text of message body for part in message.walk(): if part.get_content_type() == 'text/plain': plain_txt_msg = part # If we found plain text, decode it and return. if plain_txt_msg: msg_bytes = plain_txt_msg.get_payload(decode=True) return msg_bytes.decode(plain_txt_msg.get_content_charset()) else: return None
def send_mail(self, to, subject, body): '''Wrapper around _send_mail() which generates a Message object that it expects.''' msg = message.Message() msg.set_payload(body) msg['Subject'] = subject self._send_mail(to, msg)
def formEmail(postList): body = "" msg = message.Message() for post in postList: body += """ Title: {0} Price: {1} Description: {2} Address: {3} Link: www.kijiji.ca{4} """.format(post[0], post[3], post[1], post[2], post[5]) subject = "Kijiji Scraper: {0} Matching Posting(s) for {1}".format( str(len(postList)), searchTerm) # email_text = """ # From: {0} # To: {1} # Subject: {2} # # {3} # """.format(mail_user, mail_user, subject, body) msg.add_header("from", mail_user) msg.add_header("to", mail_receiver) msg.add_header("subject", subject) msg.set_payload(body) return msg.as_string()
def enviar_email(resumo_loja, loja): # Usando servidor gmail server = smtplib.SMTP('smtp.gmail.com:587') # f''' ''': Para formatar um bloco inteiro de texto email_content = f''' <p>Coe, Lira,</p> {resumo_loja.to_html()} <p>Tmj</p>''' msg = message.Message() msg['Subject'] = f'Lira Rules - Loja: {loja}' msg['From'] = '*****@*****.**' msg['To'] = '*****@*****.**' password = '******' msg.add_header('Content-Type', 'text/html') msg.set_payload(email_content) s = smtplib.SMTP('smtp.gmail.com: 587') # Inicializando o gmail s.starttls() # Login Credentials for sending the mail s.login(msg['From'], password) # Enviando email codificado para utf-8 s.sendmail(msg['From'], [msg['To']], msg.as_string().encode('utf-8'))
def test_message_checks(self): """Test the checks and other features of Message.""" msg = as2.Message() assert msg.content == "" assert msg.headers == {} assert msg.headers_str == b"" msg.payload = message.Message() msg.payload.set_payload(b"data") assert msg.content == b"data" org = as2.Organization(as2_name="AS2 Server") partner = as2.Partner(as2_name="AS2 Partner", sign=True) msg = as2.Message(sender=org, receiver=partner) with self.assertRaises(ImproperlyConfigured): msg.build(b"data") msg.receiver.sign = False msg.receiver.encrypt = True with self.assertRaises(ImproperlyConfigured): msg.build(b"data") msg.receiver.encrypt = False msg.receiver.mdn_mode = "ASYNC" with self.assertRaises(ImproperlyConfigured): msg.build(b"data") msg.sender.mdn_url = "http://localhost/pyas2/as2receive" msg.build(b"data")
def get_message(self, group_name, id): group = self._groupname2group(group_name) filename = '' try: id = int(id) try: article = self.get_group_article_list(group)[id - 1] filename = os.path.join(self.maildir_path, group, "cur", article) except IndexError: return None except ValueError: # Treat non-numeric ID as Message-ID try: filename = self.cache.message_bymid(id.strip())['filename'] except TypeError: # message_bymid() returned None return None try: return rfc822.Message(open(filename)) except IOError: return None
def make_part(context, request, newsletter, content, format): conversion = getMultiAdapter((context, request, newsletter), interfaces.IContentConversion, name=format) part = message.Message() set_part_payload(part, conversion.content_type, conversion.apply(content)) part['Content-Disposition'] = 'inline' return part
def do_POST(self): """ Syntax: POST Responses: 240 article posted ok 340 send article to be posted. End with <CR-LF>.<CR-LF> 440 posting not allowed 441 posting failed """ msg = rfc822.Message(io.StringIO(''.join(self.article_lines))) group_name = msg.getheader('Newsgroups') # check the 'Newsgroups' header backend = self._backend_from_group(group_name) if (not backend # No backend matches Newsgroups: header or not group_name # No Newsgroups: header or not backend.group_exists(group_name) ): # Group not found in backend self.send_response(ERR_POSTINGFAILED) return result = backend.do_POST(group_name, ''.join(self.article_lines), self.client_address[0], self.auth_username) if result == None: self.send_response(ERR_POSTINGFAILED) else: self.send_response(STATUS_POSTSUCCESSFULL)
def send_notifications(result): """ Function that will send by e-mail a notification of the state of the testing and compiling process :param result: communication-object (see communication.py) that can hold all the information about the process :return: True once the mail sent """ #Retrieving the response from system tests to send message = get_message(result) #can be changed: Email to send from and email to send to fromaddr = '*****@*****.**' toaddrs = '*****@*****.**' # setting up message fields m = e.Message() m['From'] = "*****@*****.**" m['To'] = "*****@*****.**" m['Subject'] = "Compilation and Test results" m.set_payload(message) #logging into smtp server and sending mail username = '******' password = '******' server = smtplib.SMTP('smtp.gmail.com:587') #log into smtp server.ehlo() #setting up server communication server.starttls() #start tls for secure connection server.login(username, password) #log into email account server.sendmail(fromaddr, toaddrs, m.as_string()) #sending email server.quit() return True
def sendEmail(self, agent, days, body, recipient): msg = message.Message() msg.add_header('from', 'Revision Watcher') msg.add_header('to', '*****@*****.**') temp = "REMINDER: " + agent + " revision due in " + days + "days!" msg.add_header('subject', str(temp)) msg.set_payload(body) self.mail.sendmail("Revision Sentinel", recipient, msg.as_string())
def main(reactor): m = message.Message() m.add_header("To", "*****@*****.**") m.add_header("From", "*****@*****.**") d = sendMail("*****@*****.**", "password", "mail.atleastfornow.net", 587, m) d.addCallback(print) return d
def prepare_email(mdtext, subject, recipient, sender): mdtext = recipient.salutation + ' ' + recipient.name + '\n\n' + mdtext html_content = markdown.markdown(mdtext) email_message = message.Message() email_message.add_header('From', sender) email_message.add_header('To', recipient.email) email_message.add_header('Subject', subject) email_message.add_header('MIME-Version', '1.0') email_message.add_header('Content-Type', 'text/html; charset="utf-8"') email_message.set_payload(html_content) return email_message
def api_get_score(): if 'score' in session: script_dir = os.path.dirname(__file__) file_path = os.path.join(script_dir, 'static/tests/' + session['year'] + '.json') choice = request.form.get("choice") current = session['current'] input = {} with open(file_path) as json_file: input = json.load(json_file) score = session['score'] if not results_exist(): query = """INSERT INTO resultaten (username, email, year, score) VALUES (%s, %s, %s, %s)""" conn.cursor().execute( query, (session['username'], session['email'], session['year'], str(score) + "/" + str(len(input['questions'])))) status = "Niet geslaagd" if score >= math.ceil(0.7 * len(input['questions'])): status = "Geslaagd" from_addr = '*****@*****.**' to_addr = session['email'] subject = 'Bevestiging resultaat medisch rekenen' body = 'Bevestiging van uw resultaat \'evaluatie medisch rekenen\':\n' \ 'Studentennummer: ' + session['username'] + '\n' \ 'Jaar: ' + session['year'] + '\n' \ 'Status: ' + status + '\n' \ 'Score: ' + str(score) + "/" + str(len(input['questions'])) msg = message.Message() msg.add_header('from', from_addr) msg.add_header('to', to_addr) msg.add_header('subject', subject) msg.set_payload(body) server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() server.login(from_addr, 'topsport123') server.send_message(msg, from_addr=from_addr, to_addrs=[to_addr]) server.close() session.clear() return json.dumps({ "Status": "Success", "Value": str(score) + "/" + str(len(input['questions'])) }) else: session.clear() return json.dumps({"Status": "Error"})
def send_email(self, to_addr='', subject='', body=''): from_addr = settings.CONFIG['SMTP_SETTINGS']['FROM'] msg = message.Message() msg.add_header('from', from_addr) msg.add_header('to', to_addr) msg.add_header('subject', subject) msg.set_payload(body) server = smtplib.SMTP(settings.CONFIG['SMTP_SETTINGS']['HOST'], settings.CONFIG['SMTP_SETTINGS']['PORT']) server.login(from_addr, settings.CONFIG['SMTP_SETTINGS']['PASSWORD']) server.send_message(msg, from_addr=from_addr, to_addrs=[to_addr])
def __send_mail(name: str, last_name: str, email: str): with open('config.json', 'r') as f: config = json.load(f) body = 'Welcome: %s %s' % (name, last_name) msg = message.Message() msg.add_header('from', config['WELCOME_EMAIL']['FROM']) msg.add_header('to', email) msg.add_header('subject', config['WELCOME_EMAIL']['SUBJECT']) msg.set_payload(body) smtp = SMTPEmailFactory.build() smtp.send_message(msg, from_addr=config['WELCOME_EMAIL']['FROM'], to_addrs=[email])
def send_mail_password_changed(TO, EMAIL_ADDRESS, EMAIL_PASSWORD): msgstr = "Password Changed" msg = em.Message() msg['Subject'] = 'Password Changed' msg.add_header('Content-Type', 'text/html') msg.set_payload(msgstr) s = smtplib.SMTP("smtp.outlook.com", 587) s.starttls() s.login(EMAIL_ADDRESS, EMAIL_PASSWORD) s.sendmail(EMAIL_ADDRESS, TO, msg.as_string()) s.quit()
def send_ip_changed_email(new_ip, old_ip): subject = 'IP changed' body = 'The server global IP has changed\n' + "New IP: " + new_ip + "\nOld IP: " + old_ip + "\n" msg = message.Message() msg.add_header('from', FROM_ADDRESS) msg.add_header('to', TO_ADDRESS) msg.add_header('subject', subject) msg.set_payload(body) server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(SMTP_LOGIN_NAME, SMTP_LOGIN_PASSWORD) server.send_message(msg, from_addr=FROM_ADDRESS, to_addrs=[TO_ADDRESS])
def send_mail_danger(TO, EMAIL_ADDRESS, EMAIL_PASSWORD): msgstr = '''<h1 style="text-align: center;"><font face="Tahoma">Faculty Repository System </font></h1><div><font size="4" face="Tahoma">We've changed your account password.</font></div><div><font size="4" face="Tahoma">If this was you, then you can safely ignore this mail.</font></div><div><font face="Tahoma" size="4"><br></font></div><div><font face="Tahoma" size="4">If this wasn't you, your account can be compromised, please reset your password <a href="#">RESET</a></font></div><div><font size="4" face="Tahoma"><br></font></div><div><font size="4" face="Tahoma">Regards, </font></div><div><a href="#"><font size="4" face="Tahoma">@faculty_repository_system</font></a></div>''' msg = em.Message() msg['Subject'] = 'Password Changed' msg.add_header('Content-Type', 'text/html') msg.set_payload(msgstr) s = smtplib.SMTP("smtp.outlook.com", 587) s.starttls() s.login(EMAIL_ADDRESS, EMAIL_PASSWORD) s.sendmail(EMAIL_ADDRESS, TO, msg.as_string()) s.quit()
def send_mail_password_forgot(TO, EMAIL_ADDRESS, EMAIL_PASSWORD, username, password): msgstr = "Username: {} \nTemporary Password: {}".format(username, password) msg = em.Message() msg['Subject'] = 'Password change request' msg.add_header('Content-Type', 'text/html') msg.set_payload(msgstr) s = smtplib.SMTP("smtp.outlook.com", 587) s.starttls() s.login(EMAIL_ADDRESS, EMAIL_PASSWORD) s.sendmail(EMAIL_ADDRESS, TO, msg.as_string()) s.quit()
def send_mail(TO, EMAIL_ADDRESS, EMAIL_PASSWORD, username, password): msgstr = '''<h1 style="text-align: center;"><font face="Tahoma">Faculty Repository System </font></h1><div><font size="4" face="Tahoma">We've got a request to change your account password.</font></div><div><font size="4" face="Tahoma">If this wasn't done by you, please contact us immediately so we can sort this out.</font></div><div><font size="4" face="Tahoma">Your temporary password is -</font></div><div><font size="4" face="Tahoma"><br></font></div><div><font face="Tahoma" size="4">Username: {}</font></div><div><font face="Tahoma" size="4">Password: {}</font></div><div><font face="Tahoma" size="4"><br></font></div><div><font face="Tahoma" size="4">You can't login with your old password.</font></div><div><font face="Tahoma" size="4">You can later change this password after you have logged in by clicking on hamburger menu in right-bottom corner.</font></div><div><font size="4" face="Tahoma"><br></font></div><div><font size="4" face="Tahoma">Regards, </font></div><div><a href="#"><font size="4" face="Tahoma">@faculty_repository_system</font></a></div>'''.format( username, password) msg = em.Message() msg['Subject'] = 'Password change request' msg.add_header('Content-Type', 'text/html') msg.set_payload(msgstr) s = smtplib.SMTP("smtp.outlook.com", 587) s.starttls() s.login(EMAIL_ADDRESS, EMAIL_PASSWORD) s.sendmail(EMAIL_ADDRESS, TO, msg.as_string()) s.quit()
def send_mail(receiver, subject, body): smtp_server = _config['notification']['smtp_server'] port = _config['notification']['smtp_port'] sender_email = _config['notification']['from'] password = _config['notification']['password'] receiver_email = receiver msg = message.Message() msg.add_header('from', sender_email) msg.add_header('to', receiver_email) msg.add_header('subject', subject) msg.set_payload(body) with smtplib.SMTP(smtp_server, port) as server: server.starttls() # Secure the connection server.login(sender_email, password) server.sendmail(sender_email, receiver_email, msg.as_string().encode('utf-8'))
def send_notification(episode): m = message.Message() gmail_config = config['gmail_config'] m.add_header('from', gmail_config['from_addr']) m.add_header('to', gmail_config['to_addr']) m.add_header('subject', "New " + episode['series'] + " episode downloaded!") body = episode['series'] + " (" + episode['season'] + ")\n" body = body + "\t" + episode['path'] + "\n" body = body + "\t" + episode['url'] + "\n" m.set_payload(body + '\n') server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(gmail_config['username'], gmail_config['password']) server.sendmail(gmail_config['from_addr'], gmail_config['to_addr'], m.as_string()) server.quit()
def send_mail_certificate(TO, EMAIL_ADDRESS, EMAIL_PASSWORD, name, title, source, duration, year): msgstr = '''<h1 style="text-align: center;"><font face="Tahoma">Faculty Repository System </font></h1><div><font size="4" face="Tahoma">We've seen an activity, you have uploaded a certificate as follows - </font></div><div><font size="4" face="Tahoma"><br></font></div><div><font size="4" face="Tahoma">Name : {}</font></div><div><font size="4" face="Tahoma">Title : {}</font></div><div><font size="4" face="Tahoma">Source : {}</font></div><div><font size="4" face="Tahoma">Duration : {}</font></div><div><font size="4" face="Tahoma">Year : {}</font></div><div><font size="4" face="Tahoma"><br></font></div><div><font size="4" face="Tahoma">If this was you, then you can safely ignore this mail.</font></div><div><font face="Tahoma" size="4"><br></font></div><div><font face="Tahoma" size="4">If this wasn't you, your account can be compromised, please reset your password <a href="#">RESET</a></font></div><div><font size="4" face="Tahoma"><br></font></div><div><font size="4" face="Tahoma">Regards, </font></div><div><a href="#"><font size="4" face="Tahoma">@faculty_repository_system</font></a></div>''' ''.format( name, title, source, duration, year) msg = em.Message() msg['Subject'] = 'Certificate Uploaded' msg.add_header('Content-Type', 'text/html') msg.set_payload(msgstr) s = smtplib.SMTP("smtp.outlook.com", 587) s.starttls() s.login(EMAIL_ADDRESS, EMAIL_PASSWORD) s.sendmail(EMAIL_ADDRESS, TO, msg.as_string()) s.quit()
def getEmailMessage(error_list): #--Gets text for email from subject.txt and body.txt and returns it--# import email.message as e sender_email, sender_email_password = getSenderInfo() #receiver_email = getEmailList #getting subject of email with open('/home/pi/Alert_System/subject.txt') as f: subject = f.read() #getting body of email body = getAlertMessage(error_list) msg = e.Message() msg['Subject'] = subject msg['From'] = sender_email msg.set_payload(body) return msg.as_string()
def _form_email(self, recipient_data): """ Form the html email, including mimetype and headers. """ # form the recipient and sender headers recipient = "%s <%s>" % (recipient_data.get('name'), recipient_data.get('email')) sender = "%s <%s>" % (self.from_name, self.from_email) # get the html content html_content = self._html_parser(recipient_data) # instatiate the email object and assign headers email_message = message.Message() email_message.add_header('From', sender) email_message.add_header('To', recipient) email_message.add_header('Subject', self.subject) email_message.add_header('MIME-Version', '1.0') email_message.add_header('Content-Type', 'text/plain') email_message.set_payload(html_content) return email_message.as_string()
def main(): load_dotenv() server = smtplib.SMTP('smtp.gmail.com:587') username = os.getenv("EMAIL_USERNAME") password = os.getenv("EMAIL_PASSWORD") dry_run = eval(os.getenv("DRY_RUN", True)) with open('emails.json') as emails: email_to_name_dict = json.load(emails) santas = random.sample(email_to_name_dict.items(), len(email_to_name_dict)) targets = cycle(santas) next(targets) server.ehlo() server.starttls() server.login(username, password) for (santa_email, santa_name), (target_email, target_name) in zip(santas, targets): msg = message.Message() msg.add_header('From', username) msg.add_header('To', santa_email) msg.add_header('Subject', f'Secret Santa {datetime.now().year}') msgText = f"Ho ho ho, its {santa_name}!\n\nHere's your secret santa recipient: {target_name}" \ "\n\nHappy Holidays! Please remember the gift should be about $20, or " \ "its handmade equivalent.\n\n\n\n(This is an automated email)\n\n" msg.set_payload(msgText) if dry_run == False: server.sendmail(username, santa_email, msg.as_string()) server.quit() print('\nits over!')
def build_message_root(newsletter, subscriber): msg = message.Message() msg['From'] = make_address_header('From', newsletter.author_name, newsletter.author_address) # Here we call .encode() because MailHost will assume that the headers are # strings, not header.Header instances. msg['To'] = make_address_header('To', subscriber.name, subscriber.email).encode() msg['Date'] = utils.formatdate() if newsletter.subject: msg['Subject'] = header.Header(newsletter.subject, charset=header_default_charset, header_name='Subject') if subscriber.removal_url: msg['List-Unsubscribe'] = '<%s>' % subscriber.removal_url msg['Mime-Version'] = '1.0' if (newsletter.reply_to_address and newsletter.reply_to_address != newsletter.author_address): msg['Reply-To'] = make_address_header('Reply-To', newsletter.reply_to_name, newsletter.reply_to_address) if (newsletter.sender_address and newsletter.sender_address != newsletter.author_address): msg['Sender'] = make_address_header('Sender', newsletter.sender_name, newsletter.sender_address) return msg
def mail(df, from_, password): msg = em.Message() msg.add_header('Content-Type', 'text/html') to = df['Email'].to_list() name = df['Name'].to_list() to_length = len(to) try: server = smtplib.SMTP( "smtp.outlook.com", 587) # Change it to gamil or yahoo as per requirement server.starttls() server.login(from_, password) print("Login Succesfull \n") for i, j in zip(to, name): print("" + str(to_length) + " left \n") print("Sending to {}".format(j)) data = MIMEMultipart() data['To'] = i data['From'] = from_ data['Subject'] = "Certificate" # Change subject body = "Sample Body" # Change email body data.attach(MIMEText(body, 'plain')) p = "pictures/{}.png".format(j) filename = p with open(filename) as f: attachment = f.read() # attachment = open(filename, "rb") p = MIMEBase('application', 'octet-stream') p.set_payload((attachment).read()) encoders.encode_base64(p) name = re.split("/", filename)[-1] p.add_header('Content-Disposition', "attachment; filename= %s" % name) data.attach(p) text = data.as_string() server.sendmail(from_, i, text) attachment.close() print("Sent \n") to_length -= 1 server.quit() except: print("Make sure have an active internet connection") print("Please check your credentials")
def build(self, message, status, detailed_status=None): """Function builds and signs an AS2 MDN message. :param message: The received AS2 message for which this is an MDN. :param status: The status of processing of the received AS2 message. :param detailed_status: The optional detailed status of processing of the received AS2 message. Used to give additional error info (default "None") """ # Generate message id using UUID 1 as it uses both hostname and time self.message_id = email_utils.make_msgid().lstrip('<').rstrip('>') self.orig_message_id = message.message_id # Set up the message headers mdn_headers = { 'AS2-Version': AS2_VERSION, 'ediint-features': EDIINT_FEATURES, 'Message-ID': '<{}>'.format(self.message_id), 'AS2-From': quote_as2name(message.headers.get('as2-to')), 'AS2-To': quote_as2name(message.headers.get('as2-from')), 'Date': email_utils.formatdate(localtime=True), 'user-agent': 'pyAS2 Open Source AS2 Software' } # Set the confirmation text message here confirmation_text = MDN_CONFIRM_TEXT # overwrite with organization specific message if message.receiver and message.receiver.mdn_confirm_text: confirmation_text = message.receiver.mdn_confirm_text # overwrite with partner specific message if message.sender and message.sender.mdn_confirm_text: confirmation_text = message.sender.mdn_confirm_text if status != 'processed': confirmation_text = MDN_FAILED_TEXT self.payload = MIMEMultipart( 'report', report_type='disposition-notification') # Create and attach the MDN Text Message mdn_text = email_message.Message() mdn_text.set_payload('%s\n' % confirmation_text) mdn_text.set_type('text/plain') del mdn_text['MIME-Version'] encoders.encode_7or8bit(mdn_text) self.payload.attach(mdn_text) # Create and attache the MDN Report Message mdn_base = email_message.Message() mdn_base.set_type('message/disposition-notification') mdn_report = 'Reporting-UA: pyAS2 Open Source AS2 Software\n' mdn_report += 'Original-Recipient: rfc822; {}\n'.format( message.headers.get('as2-to')) mdn_report += 'Final-Recipient: rfc822; {}\n'.format( message.headers.get('as2-to')) mdn_report += 'Original-Message-ID: <{}>\n'.format(message.message_id) mdn_report += 'Disposition: automatic-action/' \ 'MDN-sent-automatically; {}'.format(status) if detailed_status: mdn_report += ': {}'.format(detailed_status) mdn_report += '\n' if message.mic: mdn_report += 'Received-content-MIC: {}, {}\n'.format( message.mic.decode(), message.digest_alg) mdn_base.set_payload(mdn_report) del mdn_base['MIME-Version'] encoders.encode_7or8bit(mdn_base) self.payload.attach(mdn_base) # logger.debug('MDN for message %s created:\n%s' % ( # message.message_id, mdn_base.as_string())) # Sign the MDN if it is requested by the sender if message.headers.get('disposition-notification-options') and \ message.receiver and message.receiver.sign_key: self.digest_alg = \ message.headers['disposition-notification-options'].split( ';')[-1].split(',')[-1].strip().replace('-', '') signed_mdn = MIMEMultipart( 'signed', protocol="application/pkcs7-signature") del signed_mdn['MIME-Version'] signed_mdn.attach(self.payload) # Create the signature mime message signature = email_message.Message() signature.set_type('application/pkcs7-signature') signature.set_param('name', 'smime.p7s') signature.set_param('smime-type', 'signed-data') signature.add_header( 'Content-Disposition', 'attachment', filename='smime.p7s') del signature['MIME-Version'] signature.set_payload(sign_message( canonicalize(self.payload), self.digest_alg, message.receiver.sign_key )) encoders.encode_base64(signature) # logger.debug( # 'Signature for MDN created:\n%s' % signature.as_string()) signed_mdn.set_param('micalg', self.digest_alg) signed_mdn.attach(signature) self.payload = signed_mdn # Update the headers of the final payload and set message boundary for k, v in mdn_headers.items(): if self.payload.get(k): self.payload.replace_header(k, v) else: self.payload.add_header(k, v) if self.payload.is_multipart(): self.payload.set_boundary(make_mime_boundary())