def test_variable_tzname(self): t0 = datetime.datetime(1984, 1, 1, tzinfo=datetime.timezone.utc) t1 = utils.localtime(t0) self.assertEqual(t1.tzname(), 'MSK') t0 = datetime.datetime(1994, 1, 1, tzinfo=datetime.timezone.utc) t1 = utils.localtime(t0) self.assertEqual(t1.tzname(), 'EET')
def sendmail(self, toaddrs, subject, body): if isinstance(toaddrs, str): toaddrs = [toaddrs] try: port = self.mailport if not port: port = smtplib.SMTP_PORT smtp = smtplib.SMTP(self.mailhost, port) msg = EmailMessage() msg["From"] = self.fromaddr msg["To"] = ",".join(toaddrs) msg["Subject"] = subject msg["Date"] = localtime() msg.set_content(body) if self.username: if self.secure is not None: smtp.ehlo() smtp.starttls(*self.secure) smtp.ehlo() smtp.login(self.username, self.password) smtp.send_message(msg) smtp.quit() except Exception as e: print("Could not send email: {}".format(e))
def msg_response(self, report=False): msg = MIMEMultipart() msg['Date'] = format_datetime(localtime()) if self.is_matched: msg.attach(MIMEText(self.string_respone())) if self.attachment: msg.attach(self.attachment) logging.debug('MATCHER - attachment appended') elif not report: # its not ma match and its not a report logging.warning('MATCHER - unmatched response') return None if not report: msg['subject'] = self.subj else: msg.attach(MIMEText(str(self))) msg.attach(MIMEText(self.payload)) if self.is_matched: msg['subject'] = "[MATCH] {}".format(self.msg['subject']) else: msg['subject'] = "[NO MATCH] {}".format(self.msg['subject']) return msg
def emit(self, record: LogRecord) -> None: """ Emit a record. Format the record and send it to the specified addressees. """ try: msg = EmailMessage() msg["From"] = self.fromaddr msg["To"] = ",".join(self.toaddrs) msg["Date"] = localtime() msg["Subject"] = self.getSubject(record) msg.set_content(self.format(record)) smtp = SMTP_SSL( host=self.mailhost, port=self.mailport, timeout=self.timeout, context=self.context, ) smtp.login(user=self.username, password=self.password) smtp.send_message(msg=msg, from_addr=self.fromaddr, to_addrs=self.toaddrs) smtp.quit() except (KeyboardInterrupt, SystemExit): raise except Exception: self.handleError(record)
def send_new_donation(user, donation): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port")) smtp.ehlo() smtp.starttls() smtp.login(_cfg("smtp-user"), _cfg("smtp-password")) with open("emails/new_donation") as f: message = MIMEText(html.parser.HTMLParser().unescape(\ pystache.render(f.read(), { "user": user, "root": _cfg("protocol") + "://" + _cfg("domain"), "your_name": _cfg("your-name"), "amount": currency.amount("{:.2f}".format( donation.amount / 100)), "frequency": (" per month" if donation.type == DonationType.monthly else ""), "comment": donation.comment or "", }))) message['Subject'] = "New donation on fosspay!" message['From'] = _cfg("smtp-from") message['To'] = "{} <{}>".format(_cfg("your-name"), _cfg("your-email")) message['Date'] = format_datetime(localtime()) smtp.sendmail(_cfg("smtp-from"), [_cfg('your-email')], message.as_string()) smtp.quit()
def test_localtime_epoch_utc_daylight_true(self): test.support.patch(self, time, 'daylight', True) t0 = datetime.datetime(1990, 1, 1, tzinfo = datetime.timezone.utc) t1 = utils.localtime(t0) t2 = t0 - datetime.timedelta(hours=5) t2 = t2.replace(tzinfo = datetime.timezone(datetime.timedelta(hours=-5))) self.assertEqual(t1, t2)
def _prepareMessage(self): identity_key = self.fromCombo.currentData() if not identity_key: return identities = get_identities() idt = identities[identity_key] self._setHeader('Date', localtime()) self._setHeader('Subject', self.subjectEdit.text()) for header, pairs in self.rcptEdit.get_recipients().items(): self._setHeader( header, [Address(name, addr_spec=addr) for name, addr in pairs]) from_addr = Address(idt.name, addr_spec=idt.address) self._setHeader('From', from_addr) self._setHeader('Message-ID', make_msgid(domain=from_addr.domain)) for part in self.msg.iter_parts(): if part.get_content_type() == 'text/plain': part.set_content(self.messageEdit.toPlainText()) break else: self.msg.set_content(self.messageEdit.toPlainText()) return idt
def updateDatetime(self): if os.name == "nt": timestring = ntTimeString else: timestring = unixTimeString timeStr = localtime().strftime(timestring) self.vDatetime.set(timeStr)
def test_localtime_epoch_utc_daylight_false(self): test.support.patch(self, time, 'daylight', False) t0 = datetime.datetime(1990, 1, 1, tzinfo=datetime.timezone.utc) t1 = utils.localtime(t0) t2 = t0 - datetime.timedelta(hours=5) t2 = t2.replace(tzinfo=datetime.timezone(datetime.timedelta(hours=-5))) self.assertEqual(t1, t2)
def send_email(contact, msg, obj): date = format_datetime(localtime()) headers = {'Date': date} email = EmailMessage(obj, msg, to=[contact], headers=headers) try: email.send() except: print("configure email THXKBYE")
def build_message(self, jmsg): msg = EmailMessage() dt = datetime.fromtimestamp(jmsg['date'] / 1000) set_header(msg, 'Date', localtime(dt)) # set_header(msg, 'Subject', jmsg['subject']) if 'parts' in jmsg: self.build_mms(jmsg, msg) else: self.build_sms(jmsg, msg) return msg
def make_msg(subject, content, from_addr, tos=None, ccs=None, attachments=None): from_addr = parse_email(from_addr) # To have a correct address header header_registry = HeaderRegistry() header_registry.map_to_type('To', AddressHeader) msg = EmailMessage(policy.EmailPolicy(header_factory=header_registry)) msg.set_content(content) msg['From'] = from_addr msg['Subject'] = subject msg['Message-Id'] = make_msgid() if tos: msg['To'] = tos if ccs: msg['Cc'] = ccs if attachments: for att in attachments: filename = att['filename'] content = base64.b64decode(att['b64']) # Guess type here maintype, subtype = magic.from_buffer(content, mime=True).split('/') msg.add_attachment(content, maintype=maintype, subtype=subtype, filename=filename) msg['Date'] = localtime() # TODO add html alternative # See https://docs.python.org/3.6/library/email.examples.html """msg.add_alternative("\ <html> <head></head> <body> <p>{body}<p> </body> </html> "".format(content, subtype='html')""" return msg
def create_email(username, **kwargs): # subject邮件标题 string # to list or string # username email for me # content_text plain内容 # content_html html内容 # files uploadFile pk列表 cc = kwargs.get("cc", None) bcc = kwargs.get("bcc", None) subject = kwargs.get("subject", None) content_text = kwargs.get("content_text", None) to = kwargs.get("to", []) msg = EmailMessage() msg['Subject'] = subject msg['To'] = ', '.join(to) msg['Date'] = format_datetime(localtime()) msg.add_header('MIME-Version', '1.0') if cc is not None: msg['Cc'] = ', '.join(cc) if bcc is not None: msg['Bcc'] = ', '.join(bcc) msg['From'] = username msg.set_content(content_text) content_html = kwargs.get("content_html", None) if content_html is not None: # 如果有html内容,则增加进来 msg.add_alternative(content_html, subtype='html') files = kwargs.get("file_list", None) if files is not None and isinstance(files, list): # 如果有附件,将附加到邮件中 print(files) msg.add_header('X-FILE-LIST', ','.join([str(i) for i in files])) for one_pk in files: one_objs = UploadFile.objects.filter(pk=one_pk) if not one_objs.exists(): continue one_obj = one_objs.first() ctype, encoding = mimetypes.guess_type(one_obj.filename) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) with one_obj.file.open('rb') as fp: msg.add_attachment(fp.read(), maintype=maintype, subtype=subtype, filename=one_obj.filename) return msg
def send_password_reset(user): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port")) smtp.ehlo() smtp.starttls() smtp.login(_cfg("smtp-user"), _cfg("smtp-password")) message = MIMEText( render_template("emails/reset-password", user=user, root=_cfg("protocol") + "://" + _cfg("domain"), your_name=_cfg("your-name"), your_email=_cfg("your-email"))) message['Subject'] = "Reset your donor password" message['From'] = _cfg("smtp-from") message['To'] = user.email message['Date'] = format_datetime(localtime()) smtp.sendmail(_cfg("smtp-from"), [user.email], message.as_string()) smtp.quit()
def send_declined(user, amount): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port")) smtp.ehlo() smtp.starttls() smtp.login(_cfg("smtp-user"), _cfg("smtp-password")) message = MIMEText( render_template("emails/declined", user=user, root=_cfg("protocol") + "://" + _cfg("domain"), your_name=_cfg("your-name"), amount=currency.amount("{:.2f}".format(amount / 100)))) message['Subject'] = "Your monthly donation was declined." message['From'] = _cfg("smtp-from") message['To'] = user.email message['Date'] = format_datetime(localtime()) smtp.sendmail(_cfg("smtp-from"), [user.email], message.as_string()) smtp.quit()
def send(self, headers, body): self._parse_config() log.debug('SMTP host is ' + self.host + ':' + str(self.port)) if self.username: log.debug('SMTP username is ' + self.username) headers['Date'] = localtime() headers['Message-ID'] = str(uuid4()) + '@Bootini-Star' em = EmailMessage() for k, v in headers.items(): em[k] = v em.set_content(body) with smtplib.SMTP(self.host, self.port) as smtp: if self.username: smtp.starttls() smtp.login(self.username, self.password) recipient = headers['To'] if 'To' in headers else None if is_unittest_address(recipient): log.debug(f'Skipping mail to {recipient}') else: smtp.send_message(em)
def send_cancellation_notice(user, donation): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port")) smtp.ehlo() smtp.starttls() smtp.login(_cfg("smtp-user"), _cfg("smtp-password")) message = MIMEText( render_template( "emails/cancelled", user=user, root=_cfg("protocol") + "://" + _cfg("domain"), your_name=_cfg("your-name"), amount=currency.amount("{:.2f}".format(donation.amount / 100)), )) message['Subject'] = "A monthly donation on ShleePay has been cancelled" message['From'] = _cfg("smtp-from") message['To'] = f"{_cfg('your-name')} <{_cfg('your-email')}>" message['Date'] = format_datetime(localtime()) smtp.sendmail(_cfg("smtp-from"), [_cfg('your-email')], message.as_string()) smtp.quit()
def send_declined(user, amount): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port")) smtp.ehlo() smtp.starttls() smtp.login(_cfg("smtp-user"), _cfg("smtp-password")) with open("emails/declined") as f: message = MIMEText(html.parser.HTMLParser().unescape(\ pystache.render(f.read(), { "user": user, "root": _cfg("protocol") + "://" + _cfg("domain"), "your_name": _cfg("your-name"), "amount": currency.amount("{:.2f}".format(amount / 100)) }))) message['Subject'] = "Your monthly donation was declined." message['From'] = _cfg("smtp-from") message['To'] = user.email message['Date'] = format_datetime(localtime()) smtp.sendmail(_cfg("smtp-from"), [user.email], message.as_string()) smtp.quit()
def send_password_reset(user): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port")) smtp.ehlo() smtp.starttls() smtp.login(_cfg("smtp-user"), _cfg("smtp-password")) with open("emails/reset-password") as f: message = MIMEText(html.parser.HTMLParser().unescape(\ pystache.render(f.read(), { "user": user, "root": _cfg("protocol") + "://" + _cfg("domain"), "your_name": _cfg("your-name"), "your_email": _cfg("your-email") }))) message['Subject'] = "Reset your donor password" message['From'] = _cfg("smtp-from") message['To'] = user.email message['Date'] = format_datetime(localtime()) smtp.sendmail(_cfg("smtp-from"), [user.email], message.as_string()) smtp.quit()
def create_mime(self, **kwargs): '''create a mine message''' if not kwargs.get('recipient_email_addr'): raise FieldMissing('recipient_email_addr') if not kwargs.get('sender_email_addr'): raise FieldMissing('sender_email_addr') subject = kwargs.get('subject') or '' sender_display_name = kwargs.get('sender_display_name') or '' sender_email_addr = kwargs['sender_email_addr'] recipient_display_name = kwargs.get('recipient_display_name') or '' recipient_email_addr = kwargs['recipient_email_addr'] content_html = kwargs.get('content_html') or '' content_text = kwargs.get('content_text') or '' custom_header = kwargs.get( 'custom_header') # a dictionary containing customized headers message_id = make_msgid(domain=sender_email_addr.split('@')[1]) self.msg = EmailMessage() self.msg['Subject'] = subject self.msg['From'] = Address(display_name=sender_display_name, addr_spec=sender_email_addr) self.msg['To'] = Address(display_name=recipient_display_name, addr_spec=recipient_email_addr) self.msg['Date'] = localtime() self.msg.add_header('Message-Id', message_id[1:-1]) if custom_header: for key, value in custom_header.items(): self.msg.add_header(key, value) if content_text: self.msg.set_content(content_text) if content_html: self.msg.add_alternative(content_html, subtype='html') else: self.msg.set_content(content_html, subtype='html') return self.msg
def send_cancellation_notice(user, donation): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port")) smtp.ehlo() smtp.starttls() smtp.login(_cfg("smtp-user"), _cfg("smtp-password")) with open("emails/cancelled") as f: message = MIMEText(html.parser.HTMLParser().unescape(\ pystache.render(f.read(), { "user": user, "root": _cfg("protocol") + "://" + _cfg("domain"), "your_name": _cfg("your-name"), "amount": currency.amount("{:.2f}".format( donation.amount / 100)), }))) message['Subject'] = "A monthly donation on fosspay has been cancelled" message['From'] = _cfg("smtp-from") message['To'] = "{} <{}>".format(_cfg("your-name"), _cfg("your-email")) message['Date'] = format_datetime(localtime()) smtp.sendmail(_cfg("smtp-from"), [_cfg('your-email')], message.as_string()) smtp.quit()
def send_new_donation(user, donation): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port")) smtp.ehlo() smtp.starttls() smtp.login(_cfg("smtp-user"), _cfg("smtp-password")) message = MIMEText( render_template( "emails/new_donation", user=user, root=_cfg("protocol") + "://" + _cfg("domain"), your_name=_cfg("your-name"), amount=currency.amount("{:.2f}".format(donation.amount / 100)), frequency=(" per month" if donation.type == DonationType.monthly else ""), comment=donation.comment or "")) message['Subject'] = "New donation on ShleePay!" message['From'] = _cfg("smtp-from") message['To'] = f"{_cfg('your-name')} <{_cfg('your-email')}>" message['Date'] = format_datetime(localtime()) smtp.sendmail(_cfg("smtp-from"), [_cfg('your-email')], message.as_string()) smtp.quit()
def emit(self, record): """ Emit a record. """ try: port = self.mailport if not port: port = smtplib.SMTP_PORT smtp = smtplib.SMTP_SSL(self.mailhost, port, timeout=self.timeout) msg = EmailMessage() msg['From'] = self.fromaddr msg['To'] = ','.join(self.toaddrs) msg['Subject'] = self.getSubject(record) msg['Date'] = em.localtime() msg.set_content(self.format(record)) if self.username: smtp.login(self.username, self.password) smtp.send_message(msg, self.fromaddr, self.toaddrs) smtp.quit() except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record)
def updateDatetime(self): if os.name == 'nt': timestring = ntTimeString else: timestring = unixTimeString timeStr = localtime().strftime(timestring) self.vDatetime.set(timeStr)
def test_localtime_daylight_false_dst_true(self): test.support.patch(self, time, 'daylight', False) t0 = datetime.datetime(2012, 3, 12, 1, 1) t1 = utils.localtime(t0, isdst=1) t2 = utils.localtime(t1) self.assertEqual(t1, t2)
def test_localtime_is_tz_aware_daylight_false(self): test.support.patch(self, time, 'daylight', False) t = utils.localtime() self.assertIsNot(t.tzinfo, None)
def enviar_correo(self, correo_dest, asunto, cuerpo, intento=0, *rutas_adjuntos): """ Se envía un correo bajo el nombre indicado a mailer y sobre la conexión establecida en este, con los elementos cómunes de un correo, que se le pasan como argumentos. :param correo_dest: :param asunto: :param cuerpo: :param intento: para indicar el número de reintento. :param rutas_adjuntos: :return: """ if True in (type(x) is not str for x in (correo_dest, asunto, cuerpo)): raise Exception(__name__ + '.sendMail params must be str') if self.smtp_host == 'smtp.sendgrid.net': origen = '*****@*****.**' else: origen = self.email_origen enviado = False # Podríamos verificar cnx sigue, aunque sino ya saltara excepción. try: # Preparamos las cabeceras de addrs fromadrr = Address(self.nombre_origen, addr_spec=origen) name, addr = parseaddr(correo_dest) toaddr = Address(name, addr_spec=addr) # Encapsulamos el mensaje msg = MIMEMultipart() # Para poder combinar fragmentos de <> MIME msg['From'] = formataddr((fromadrr.display_name, fromadrr.addr_spec)) msg['To'] = formataddr((toaddr.display_name, toaddr.addr_spec)) msg['Subject'] = asunto msg['Date'] = format_datetime(localtime()) # Construir msg (MIME de texto) y añadir al contenedor msg.attach(MIMEText(cuerpo, 'plain')) # Adición de los adjuntos, a msg. for ruta in rutas_adjuntos: rutap = os.path.abspath(ruta) if not os.path.exists(rutap): # notificarlo de alguna forma print('{} error:\t fallo adjuntando {} para {}'.format( __name__, rutap, origen)) continue #with open(rutap) as fp: # part = MIMEText(fp.read(), _subtype='plain') part = MIMEBase('application', "octet-stream") part.set_payload(open(rutap, "rb").read()) encoders.encode_base64(part) # part.add_header('Content-Disposition', # 'attachment; filename="{}"'.format(os.path.basename(rutap))) part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(os.path.basename(rutap))) msg.attach(part) # server.sendmail(fromadrr.addr_spec, tomail, msg.as_string()) self.smtpserver.send_message(msg) enviado = True self._incr_numenviados() except SMTPException as smtpe: print('RECONECTADO y REENVIO POR EXCEPT') if intento < mailer.REINTENTOS and not enviado: self._conectar() self.enviar_correo(correo_dest, asunto, cuerpo, intento+1, *rutas_adjuntos) else: raise except: raise
def test_localtime_epoch_notz_daylight_false(self): test.support.patch(self, time, 'daylight', False) t0 = datetime.datetime(1990, 1, 1) t1 = utils.localtime(t0) t2 = utils.localtime(t0.replace(tzinfo=None)) self.assertEqual(t1, t2)
def test_localtime_is_tz_aware_daylight_false(self): test.support.patch(self, time, 'daylight', False) t = utils.localtime() self.assertIsNotNone(t.tzinfo)
def _hack(self, message): znow = zdatetime.now() znow = utils.localtime(znow) self.local_date = znow.strftime(format=self.LFORMAT) self.message = str(message)
''' special notice: most email web has to open SMTP/POP by yourself in setting after opening SMTP/POP, you should replace mypassword with serial code given by email web instead of your login pw. If not, may raise 535 error ''' myfromaddr = input("From: ") #input email fromaddress mypassword = getpass.getpass("Password: "******"To: ")#input email toaddress mysmtpserver = "smtp.qq.com" #use qq email here #official doc: MIMEText(_text,_subtype='plain',charset=None,*,policy=compat32) mymsgcontent = "hello, through the Great Wall, we'll see a bigger world.;->" sendtime="\nSEND TIME: " + localtime().strftime("%Y-%m-%d %H:%M:%S") mymsg = MIMEText(mymsgcontent+sendtime,'plain','utf-8') ''' official doc: class smtplib.SMTP(host='',port=0,local_hostname=None,[timeout]source_address=None) ''' serverport = 25 #SMTP default port is 25 server = smtplib.SMTP(mysmtpserver,serverport) server.starttls() # sending email in a safe way server.set_debuglevel(1) # 1 for debug msg shown, 2 for level results in these messages being timestamped server.login(myfromaddr,mypassword) server.sendmail(myfromaddr,[mytoaddr],mymsg.as_string())#mytoaddr is in list cause you may send email to a group server.quit() '''
''' special notice: most email web has to open SMTP/POP by yourself in setting after opening SMTP/POP, you should replace mypassword with serial code given by email web instead of your login pw. If not, may raise 535 error ''' myfromaddr = input("From: ") #input email fromaddress mypassword = getpass.getpass("Password: "******"To: ") #input email toaddress mysmtpserver = "smtp.qq.com" #use qq email here #official doc: MIMEText(_text,_subtype='plain',charset=None,*,policy=compat32) mymsgcontent = "hello, through the Great Wall, we'll see a bigger world.;->" sendtime = "\nSEND TIME: " + localtime().strftime("%Y-%m-%d %H:%M:%S") mymsg = MIMEText(mymsgcontent + sendtime, 'plain', 'utf-8') ''' official doc: class smtplib.SMTP(host='',port=0,local_hostname=None,[timeout]source_address=None) ''' serverport = 25 #SMTP default port is 25 server = smtplib.SMTP(mysmtpserver, serverport) server.starttls() # sending email in a safe way server.set_debuglevel( 1 ) # 1 for debug msg shown, 2 for level results in these messages being timestamped server.login(myfromaddr, mypassword) server.sendmail(myfromaddr, [ mytoaddr ], mymsg.as_string()) #mytoaddr is in list cause you may send email to a group
def test_localtime_epoch_utc_daylight_false(self): test.support.patch(self, time, 'daylight', False) t0 = datetime.datetime(1970, 1, 1, tzinfo = datetime.timezone.utc) t1 = utils.localtime(t0) self.assertEqual(t0, t1)
def test_localtime_is_tz_aware_daylight_true(self): test.support.patch(self, time, 'daylight', True) t = utils.localtime() self.assertIsNotNone(t.tzinfo)
def test_localtime_is_tz_aware_daylight_true(self): test.support.patch(self, time, 'daylight', True) t = utils.localtime() self.assertIsNot(t.tzinfo, None)
if smtp_server is None: continue break except (socket.gaierror, TimeoutError, ConnectionRefusedError) as err: print(f'{whoami} unable to connect to smtp server “{server}”: {err}', file=sys.stderr) if smtp_server is None: sys.exit('No viable SMTP server') smtp_server.set_debuglevel(args.debug_level) # Set up the message parts. msg = MIMEMultipart('alternative') msg['Message-ID'] = make_msgid() msg['Date'] = format_datetime(localtime()) msg['From'] = args.from_addr msg['Subject'] = args.subject msg['To'] = ', '.join(args.to_addr) if args.cc_addr is not None: msg['Cc'] = ', '.join(args.cc_addr) if args.bcc_addr is not None: msg['Bcc'] = ', '.join(args.bcc_addr) if args.reply_addr is not None: msg['Reply-To'] = args.reply_addr # Plain text body if no files specified if args.html_file is None and args.text_file is None: text_body = '' while True: try:
to_addr = Address(display_name=outmsg['to_name'], addr_spec=outmsg['to_email']) msg['To'] = to_addr.__str__() if outmsg['reply_email']: reply_addr = Address(display_name=(outmsg['reply_name'] or ''), addr_spec=outmsg['reply_email']) msg['Reply-To'] = reply_addr.__str__() logging.debug(u'Reply-To %s', msg['Reply-To']) if outmsg['body_text']: msg.attach(MIMEText(outmsg['body_text'], 'plain')) if outmsg['body_html']: msg.attach(MIMEText(outmsg['body_html'], 'html')) # msg.add_header('Message-Id', make_msgid(domain=from_addr.domain)) msg.add_header('Date', format_datetime(localtime(), True)) logging.debug(u'Sending email') smtpconn.send_message(msg) curs.execute('SELECT pgmailer.sender_complete(%s)', (outmsg_id,)) logging.debug(u'Outmsg #%s sended', outmsg_id) except Exception: logging.error(u'%s', sys.exc_info()[1].args[0]) curs.execute('SELECT pgmailer.sender_error(%s, %s::text)', (outmsg_id, sys.exc_info()[1].args[0])) smtpconn = None time.sleep(10)