def SendEmail(to_addrs, title, msg, type="html", from_name=Config.EMALL_USER, toHander=None): """ 发送邮件 :param to_addrs: 接收方的邮件地址 :param title: 邮件标题 :param msg: 邮件内容 :param type: 邮件类型 :param from_name: 发送方名字 :param toHander: 自定义头 :return: """ mail_encoding = 'utf-8' # 发件人 sender = (from_name, Config.EMALL_USER) # 收件人 recipients = to_addrs if toHander is not None: recipients = toHander # 主题 subject = title if type == 'html': payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail( \ sender, \ recipients, \ subject, \ mail_encoding, \ ("", mail_encoding), \ html=(msg, mail_encoding)) else: payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail( \ sender, \ recipients, \ subject, \ mail_encoding, \ (msg, mail_encoding), \ html=None) try: smtp = GetSmtp() smtp.sendmail(Config.EMALL_USER, to_addrs, payload) return True except Exception as ex: print(ex.message) raise ex return False
def send_email(title, content, send_filepaths): email_sender = conf.SMTP_LOGIN email_receivers = conf.EMAIL_RECEIVERS.split(';') smtp_host = conf.SMTP_HOST smtp_port = conf.SMTP_PORT smtp_mode = conf.SMTP_MODE smtp_login = conf.SMTP_LOGIN smtp_password = conf.SMTP_PASSWORD import pyzmail attach_files = [] for send_filepath in send_filepaths: filename = os.path.basename(send_filepath) attach_file = (open(send_filepath).read(), 'application', 'octet-stream', filename, '') attach_files.append(attach_file) payload, mail_from, rcpt_to, msg_id=pyzmail.compose_mail(email_sender, \ email_receivers, title, \ 'utf-8', None, html=(content, 'utf-8'), attachments=attach_files) ret=pyzmail.send_mail(payload, email_sender, rcpt_to, smtp_host, \ smtp_port=smtp_port, smtp_mode=smtp_mode, \ smtp_login=smtp_login, smtp_password=smtp_password) print(ret)
def send_mail(self, sender, to, subject, text, html=None, reply_to=None): """ Send email to user. """ encoding = 'utf-8' text_args = (text, encoding) html_args = (html, encoding) if html else None headers = [] if reply_to: headers.append(('Reply-To', reply_to)) payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail( sender, [to], subject, encoding, text_args, html=html_args, headers=headers) try: pyzmail.send_mail2(payload, mail_from, rcpt_to, **self.smtp_params) except Exception as e: logger.exception('Unable to send email to the receipient.') raise Exception('Unable to send email to the receipient.')
def send_mail(sender, recipients, subject, text_content, headers=[]): """ Sends email using pyzmail """ prefered_encoding = 'iso-8859-1' text_encoding = 'iso-8859-1' smtp_host = EMAIL_HOST smtp_port = EMAIL_PORT smtp_mode = 'tls' if EMAIL_USE_TLS else 'normal' smtp_login = EMAIL_HOST_USER if EMAIL_HOST_USER != '' else None smtp_password = EMAIL_HOST_PASSWORD if EMAIL_HOST_USER != '' else None payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail( ("Reuse Mobile", sender), recipients, subject, prefered_encoding, (text_content, text_encoding), html=None, headers=headers) ret = pyzmail.send_mail(payload, mail_from, rcpt_to, smtp_host, smtp_port=smtp_port, smtp_mode=smtp_mode, smtp_login=smtp_login, smtp_password=smtp_password) if isinstance(ret, dict): if ret: return 'failed recipients:' + ','.join(ret.keys()) else: return 'success' else: return 'error: ' + ret + "\n\n "+ ' from: ' + mail_from + " host: " +smtp_host+" port: "+ str(smtp_port) + " mode: " + smtp_mode + " login: "******" password: " + str(smtp_password)
def postino_raw(text=None, html=None, subject=None, to=[], cc=[], bcc=[], cfg=None): if cfg is None: raise PostinoError('No configuration specified') if subject is None: raise PostinoError('No subject specified') if text is None and html is None: raise PostinoError('No body specified') if not compat.isunicode(subject): raise PostinoError('Subject must be a unicode string') if not (compat.isunicode(text) or compat.isunicode(html)): raise PostinoError('Body must be a unicode string') if not to: raise PostinoError('No recipients') for addr in to + cc + bcc: if not isinstance(addr, Address): raise PostinoError('Address of invalid type') def encode_text(text, encoding='utf-8'): if text is None: return None return (text.encode(encoding), encoding) convert_address = lambda addr: addr.to_pyzmail() convert_addresses = lambda a: [convert_address(e) for e in a] # all looks OK, create and send the email payload, mail_from, rcpt_to, msg_id = compose_mail( convert_address(cfg.sender), convert_addresses(to), cc=convert_addresses(cc), bcc=convert_addresses(bcc), subject=subject.replace('\n', ' ').strip(), default_charset='utf-8', text=encode_text(text), html=encode_text(html)) ret = send_mail(payload, mail_from, rcpt_to, cfg.server, smtp_port=cfg.port, smtp_mode=cfg.mode, smtp_login=cfg.login, smtp_password=cfg.password) if ret: raise PostinoError('Failed sending: %s' % ret)
def compose_mail(grading, recv_email): return pyzmail.compose_mail( text=(compose_message(grading), "utf-8"), sender=(u"Javalabra", "*****@*****.**"), recipients=[(grading[0], recv_email)], subject="Javalabra 2014-3: Arvosanasi", default_charset="utf-8", )
def compose_mail(grading, recv_email): return pyzmail.compose_mail( text=(compose_message(grading), 'utf-8'), sender=(u'Javalabra', '*****@*****.**'), recipients=[(grading[0], recv_email)], subject='Javalabra 2014-3: Arvosanasi', default_charset='utf-8', )
def send_mail_from_note(note, smtp_host, smtp_port, smtp_login, smtp_password, smtp_mode, sender, to, debug=False, verbose=False): counter = 1 resources = {} images = [] if note.resources: for r in note.resources: k = r.data.bodyHash.encode('hex') fn = '%.2i.%s' % (counter, mimetypes.guess_extension(r.mime)[1:]) resources[k] = 'cid:' + fn a, b = r.mime.split('/') images.append((r.data.body, a, b, fn, None)) counter += 1 text_content = PlainTextOfENML(note.content) html_content = HTMLOfENML(note.content, resources) title = note.title #title = 'La note de %sh' % datetime.now().strftime('%H') try: payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail( sender=sender, recipients=to, subject=title, default_charset='utf-8', text=(text_content, 'utf-8'), html=(html_content, 'utf-8'), attachments=None, embeddeds=images,) #headers=(('Reply-To', '*****@*****.**' % str(note.guid)), )) ret = pyzmail.send_mail(payload=payload, mail_from=mail_from, rcpt_to=rcpt_to, smtp_host=smtp_host, smtp_port=smtp_port, smtp_mode=smtp_mode, smtp_login=smtp_login, smtp_password=smtp_password) if isinstance(ret, dict): if ret: if verbose: print >> sys.stderr, 'failed recipients:', ', '.join(ret.keys()) else: if verbose: print >> sys.stderr, 'success' else: if verbose: print >> sys.stderr, 'error:', ret except Exception, e: raise return 1
def SendEmail(to_addrs, title, msg, type="plain", from_name=Config.EMALL_USER, toHander=None): mail_encoding = 'utf-8' # 发件人 sender = (from_name, Config.EMALL_USER) # 收件人 recipients = to_addrs if toHander is not None: recipients = toHander # 主题 subject = title if type == 'html': payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail( \ sender, \ recipients, \ subject, \ mail_encoding, \ ("", mail_encoding), \ html=(msg, mail_encoding)) else: payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail( \ sender, \ recipients, \ subject, \ mail_encoding, \ (msg, mail_encoding), \ html=None) try: smtp = GetSmtp() smtp.sendmail(Config.EMALL_USER, to_addrs, payload) return True except Exception, ex: print ex.message raise ex return False
def alert(game): text = "There's a Giants game tomorrow at AT&T park. The game should end around %s. Plan accordingly. Game end time : %s" % ( game.strftime("%I:%M %p"), game.strftime("%c")) logging.debug("Emailing : %s" % text) compose_args = { 'sender': ("Is there a Giants game tomorrow", SENDER), 'recipients': [RECIPIENT], 'subject': "There's a Giants game tomorrow", 'default_charset': 'iso-8859-1', 'text': (text, 'us-ascii') } payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail(**compose_args) return pyzmail.send_mail(payload, mail_from, rcpt_to, 'localhost')
def send_email_pyzmail(self, maildict): """Send a mail message. pyzmail is supposed to be good but my experience with it has been terrible. It fails mysteriously and takes minutes to time out. and the compose_mail function seems to return broken value from mail_from return argument. """ # mail settings mailsettings = self.get_setting_value(mconst.DEF_SETTINGSEC_mail) # parameters efrom = mailsettings['mail_from'] eto = maildict['to'] esubject = maildict['subject'] ebody = maildict['body'] preferred_encoding = 'iso-8859-1' text_encoding = preferred_encoding # ensure eto is a list if (isinstance(eto, basestring)): eto = [eto] # compose email and create payload (payload, mail_from, rcpt_to, msg_id) = pyzmail.compose_mail(efrom, eto, esubject, preferred_encoding, (ebody,text_encoding)) # ATTN: return value of mail_from is bad, and was causing failure to send email for hours before identified #print payload #msg = pyzmail.PyzMessage.factory(payload) #print msg.get_subject() #print "MAIL SETTINGS: "+str(mailsettings) #print "MAIL FROM: "+mail_from #print "MAIL TO: "+str(rcpt_to) # smtp info for sending smtp_host = mailsettings['smtp_host'] smtp_port = mailsettings['smtp_port'] smtp_mode = mailsettings['smtp_mode'] smtp_login = mailsettings['smtp_login'] smtp_password = mailsettings['smtp_password'] # actually send the mail ret=pyzmail.send_mail(payload, efrom, eto, smtp_host=smtp_host, smtp_port=smtp_port, smtp_mode=smtp_mode, smtp_login=smtp_login, smtp_password=smtp_password) # check return value if isinstance(ret, dict): if ret: return EFailure('failed recipients: ' + ', '.join(ret.keys())) else: return None return EFailure('error:'+ ret)
def sendEmail(overview, body, log_file_attachments): #encoded inline image logo=base64.b64decode( """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 """) #Get Current Date & Time datetime_string = datetime.datetime.now().strftime('%A, %B %d, %Y | %H:%M%p %Z') #Create Email Template text_content=u'Daily Nodealyzer Report Content' with open (script_dir + "/email_template_inlined.html", "r") as template: html_content=template.read().replace('\n', '') #Fill in Template Information html_content = html_content.replace('[ENCODED_LOGO]', '<img src="cid:logo"/>') html_content = html_content.replace('[DATE_TIME]', datetime_string) html_content = html_content.replace('[TITLE]', 'Daily Nodealyzer Report') html_content = html_content.replace('[SUBTITLE]', config.get('ServerInfo','friendly_server_name')) html_content = html_content.replace('[PANEL]', overview) html_content = html_content.replace('[BODY]', body) html_content = html_content.replace('[FOOTER]', 'Generated by <a href="https://www.github.com/sciguy14/Nodealyzer" title="Nodealyzer on GitHub">Nodealyzer</a>') #Generate Log File attachment list attachment_list = [] for filename in log_file_attachments: with open (filename, "r") as attachment_file: attachment_text=attachment_file.read() attachment_list.append([attachment_text, 'text', 'plain', filename, 'us-ascii']) payload, mail_from, rcpt_to, msg_id=pyzmail.compose_mail(\ (config.get('ServerInfo','friendly_server_name'), config.get('ServerInfo','server_email')), \ [(config.get('OwnerInfo','owner_name'), config.get('OwnerInfo','owner_email')),], \ u'Daily Nodealyzer Report', \ 'iso-8859-1', \ (text_content, 'iso-8859-1'), \ (html_content, 'iso-8859-1'), \ embeddeds=[(logo, 'image', 'gif', 'logo', None)], \ attachments=attachment_list ) ret=pyzmail.send_mail(payload, mail_from, rcpt_to, config.get('ServerInfo','smtp_host'), \ smtp_port=config.get('ServerInfo','smtp_port'), smtp_mode=config.get('ServerInfo','smtp_mode'), \ smtp_login=config.get('ServerInfo','smtp_login'), smtp_password=config.get('ServerInfo','smtp_password')) if isinstance(ret, dict): if ret: return 'Failed recipients:', ', '.join(ret.keys()) else: return 'Success!' else: return 'Error:', ret
def send_email(title, content, send_filepath): import pyzmail filename = os.path.basename(send_filepath) attach_file = (open(send_filepath).read(), 'application', 'octet-stream', filename, '') payload, mail_from, rcpt_to, msg_id=pyzmail.compose_mail(email_sender, \ email_receivers, \ title, \ 'utf-8', None, html=(content, 'utf-8'), attachments=[attach_file]) ret=pyzmail.send_mail(payload, email_sender, rcpt_to, smtp_host, \ smtp_port=smtp_port, smtp_mode=smtp_mode, \ smtp_login=smtp_login, smtp_password=smtp_password) print(ret)
def alert(game): text = ( "There's a Giants game tomorrow at AT&T park. The game should end around %s. Plan accordingly. Game end time : %s" % (game.strftime("%I:%M %p"), game.strftime("%c")) ) logging.debug("Emailing : %s" % text) compose_args = { "sender": ("Is there a Giants game tomorrow", SENDER), "recipients": [RECIPIENT], "subject": "There's a Giants game tomorrow", "default_charset": "iso-8859-1", "text": (text, "us-ascii"), } payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail(**compose_args) return pyzmail.send_mail(payload, mail_from, rcpt_to, "localhost")
def send_email_pyzmail(self, maildict): """Send a mail message. pyzmail is supposed to be good but my experience with it has been terrible. It fails mysteriously and takes minutes to time out. and the compose_mail function seems to return broken value from mail_from return argument. """ # mail settings mailsettings = self.get_setting_value(mconst.DEF_SETTINGSEC_mail) # parameters efrom = mailsettings['mail_from'] eto = maildict['to'] esubject = maildict['subject'] ebody = maildict['body'] preferred_encoding = 'iso-8859-1' text_encoding = preferred_encoding # compose email and create payload payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail(efrom, eto, esubject, preferred_encoding, (ebody,text_encoding)) # ATTN: return value of mail_from is bad, and was causing failure to send email for hours before identified #print payload #msg = pyzmail.PyzMessage.factory(payload) #print msg.get_subject() #print "MAIL SETTINGS: "+str(mailsettings) #print "MAIL FROM: "+mail_from #print "MAIL TO: "+str(rcpt_to) # smtp info for sending smtp_host = mailsettings['smtp_host'] smtp_port = mailsettings['smtp_port'] smtp_mode = mailsettings['smtp_mode'] smtp_login = mailsettings['smtp_login'] smtp_password = mailsettings['smtp_password'] # actually send the mail ret=pyzmail.send_mail(payload, efrom, eto, smtp_host=smtp_host, smtp_port=smtp_port, smtp_mode=smtp_mode, smtp_login=smtp_login, smtp_password=smtp_password) # check return value if isinstance(ret, dict): if ret: return EFailure('failed recipients: ' + ', '.join(ret.keys())) else: return None return EFailure('error:'+ ret)
def send(self, mail_header, text='', html=None, file_list=None): # 构造邮件 payload, mail_from, rcpt_to, msg_id = smtp.compose_mail( (self.__conf['profile']['name'], self.__conf['profile']['mailbox']), mail_header['recipients'], mail_header['subject'], 'UTF-8', (text, 'UTF-8'), None if html is None else (html, 'UTF-8'), [] if file_list is None else Mail.__add_attachments(file_list), headers=mail_header['others'] if mail_header.has_key('others') else []) # 发送邮件 ret = smtp.send_mail(payload, mail_from, rcpt_to, self.__conf['smtp']['server'], self.__conf['smtp']['port'], self.__conf['smtp']['mode'], self.__conf['profile']['account'], self.__conf['profile']['password']) # 发生错误 if not isinstance(ret, dict): log.error('Send error: ' + ret) return False else: # 发送至某些收件人失败 if ret: log.warning('Failed recipients: ') for recipient, (code, msg) in ret.iteritems(): log.warning('code: %d recipient: %s error: %s', code, recipient, msg) return False # 发送成功 log.info('Send to %s success.' % (rcpt_to)) return True
def SendMessage(self, subject, msg): payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail( self.sender, self.recipients, unicode(subject), self.default_charset, (msg, self.encoding)) ret = pyzmail.send_mail(payload, mail_from, rcpt_to, self.smtp_host, self.smtp_port, self.smtp_mode, self.smtp_login, self.smtp_password) if isinstance(ret, dict): if ret: str = 'failed recipients:' + ', '.join(ret.keys()) raise SendMail.SendMailException(str) # print 'failed recipients:', ', '.join(ret.keys()) #else: # print 'success' else: str = 'error:' + ret raise SendMail.SendMailException(str)
def send_email: sender = (u'Security Force', '*****@*****.**') recipients = [(u'Boss', '*****@*****.**')] ''' subject = u'Notification of a security breach' text_content = u'You have been alerted of an alleged security breach of your safe. Stay protected.' ''' subject = u'Test message' text_content = u'This is a test message.' prefered_encoding = 'iso-8859-1' text_encoding = 'iso-8859-1' payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail(\ sender, \ recipients, \ subject, \ prefered_encoding, \ (text_content, text_encoding), \ html=None)#, \ #attachments=[('attached content', 'text', 'plain', 'text.txt', \ # 'us-ascii')]) print payload print "------------------------------------------------------------" print 'Sender address: ', mail_from print 'Recipients: ', rcpt_to print "------------------------------------------------------------" smtp_host = "smtp.gmail.com" smtp_port = 587 smtp_mode = 'tls' smtp_login = '******' smtp_password = '******' ret = pyzmail.send_mail(payload, mail_from, rcpt_to, smtp_host, \ smtp_port=smtp_port, smtp_mode=smtp_mode, \ smtp_login=smtp_login, smtp_password=smtp_password) if isinstance(ret, dict): if ret: print 'failed recipients: ', ', '.join(ret.keys()) else: print 'Boss has been alerted about the situation.' else: print 'error: ', ret
def assemble_email(blob): _from = blob['fields']['from'][0] def flat_addresses(field): return [(a['name'], a['email']) if a.get('name') else a['email'] for a in blob['fields'][field]] _texts = filter(lambda x: x['type'] == 'text', blob['fields']['body']) _htmls = filter(lambda x: x['type'] == 'html', blob['fields']['body']) mtext = (_texts[0]["value"].encode(CHARSET), CHARSET) if _texts else None mhtml = (_htmls[0]["value"].encode(CHARSET), CHARSET) if _htmls else None headers = [ ('User-Agent', 'curie'), ('Message-Id', blob["fields"]["message_id"]), ] in_reply_to = blob["fields"].get("in-reply-to") references = blob["fields"].get("references") if in_reply_to: headers.append(('In-Reply-To', in_reply_to)) if references: headers.append(('References', ",".join(references))) #sender, recipients, subject, default_charset, text, html=None, attachments=[], embeddeds=[], cc=[], bcc=[], message_id_string=None, date=None, headers=[]) payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail( (_from.get('name'), _from.get('email')), flat_addresses('to'), blob['fields']['subject'], CHARSET, mtext, html = mhtml, attachments = [], embeddeds = [], cc = flat_addresses('cc'), bcc = flat_addresses('bcc'), headers = headers, ) return payload, mail_from, rcpt_to, msg_id
def send_glenta(to, buy_for): message = MESSAGE % (to[0], buy_for) mail, mail_from, mail_to, msg_id = pyzmail.compose_mail( SMTP['from'], [to], SUBJECT, 'utf-8', (message.encode('iso-8859-1'), 'iso-8859-1') ) result = pyzmail.send_mail( mail, mail_from, mail_to, SMTP['host'], smtp_port=SMTP['port'], smtp_mode=SMTP['mode'], smtp_login=SMTP['login'], smtp_password=SMTP['password'] ) print result
def compose_email(self): # Define variables to use text_content = self.msg preferred_encoding = 'iso-8859-1' text_encoding = 'iso-8859-1' # date = email.utils.formatdate(time.time(), localtime=True) # Compose the email in payload, mail_from, rcpt_to, msg_id payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail( (self.sender, self.sender), self.recipients, self.subject, preferred_encoding, (text_content, text_encoding), html=None, attachments=self.attachments) return payload, mail_from, rcpt_to, msg_id
def assemble_email(blob): _from = blob['fields']['from'][0] def flat_addresses(field): return [(a['name'], a['email']) if a.get('name') else a['email'] for a in blob['fields'][field]] _texts = filter(lambda x: x['type'] == 'text', blob['fields']['body']) _htmls = filter(lambda x: x['type'] == 'html', blob['fields']['body']) mtext = (_texts[0]["value"].encode(CHARSET), CHARSET) if _texts else None mhtml = (_htmls[0]["value"].encode(CHARSET), CHARSET) if _htmls else None headers = [ ('User-Agent', 'curie'), ('Message-Id', blob["fields"]["message_id"]), ] in_reply_to = blob["fields"].get("in-reply-to") references = blob["fields"].get("references") if in_reply_to: headers.append(('In-Reply-To', in_reply_to)) if references: headers.append(('References', ",".join(references))) #sender, recipients, subject, default_charset, text, html=None, attachments=[], embeddeds=[], cc=[], bcc=[], message_id_string=None, date=None, headers=[]) payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail( (_from.get('name'), _from.get('email')), flat_addresses('to'), blob['fields']['subject'], CHARSET, mtext, html=mhtml, attachments=[], embeddeds=[], cc=flat_addresses('cc'), bcc=flat_addresses('bcc'), headers=headers, ) return payload, mail_from, rcpt_to, msg_id
def sendmail(sender,recipients,subject,msg='',attach=[]): payload, mail_from, rcpt_to, msg_id=pyzmail.compose_mail(\ sender, \ recipients, \ subject, \ 'utf-8', \ (msg, 'utf-8'), \ html=None, \ attachments=attach) #[('attached content', 'text', 'plain', 'text.txt', 'utf-8')] smtp_host = SMTP_HOST ret=pyzmail.send_mail(payload, mail_from, rcpt_to, smtp_host, smtp_port=smtp['port'], smtp_mode=smtp['mode'],smtp_login=smtp['username'],smtp_password=smtp['password']) if isinstance(ret, dict): if ret: print('failed recipients:', ', '.join(ret.keys())) else: print('error:', ret)
def compose_email(self): # Define variables to use text_content = self.msg preferred_encoding = 'iso-8859-1' text_encoding = 'iso-8859-1' # date = email.utils.formatdate(time.time(), localtime=True) # Compose the email in payload, mail_from, rcpt_to, msg_id payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail( self.sender, self.recipients, self.subject, preferred_encoding, (text_content, text_encoding), html=None, attachments=self.attachments) return payload, mail_from, rcpt_to, msg_id
def send_mail(self, sender, to, subject, text, html=None, reply_to=None): """ Send email to user. Arguments: sender - (string or tuple) email or a tuple of the form ('Name', '*****@*****.**') to - (string) - recipient address subject - (str) The subject of the message text - (tuple or None) The text version of the message html - (tuple or None) The HTML version of the message reply_to - (string or tuple) email or a tuple of the form ('Name', '*****@*****.**') """ encoding = 'utf-8' text_args = (text, encoding) html_args = (html, encoding) if html else None headers = [] reply_to_tuple = self._convert_email_tuple(reply_to) sender_tuple = self._convert_email_tuple(sender) if reply_to_tuple and reply_to_tuple[1]: # only append header when there is reply to email reply_to_value = pyzmail.generate.format_addresses( [ reply_to_tuple, ], header_name='Reply-To', charset=encoding) headers.append(('Reply-To', reply_to_value)) payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail( sender_tuple, [to], subject, encoding, text_args, html=html_args, headers=headers) try: pyzmail.send_mail2(payload, mail_from, rcpt_to, **self.smtp_params) except Exception: logger.exception('Unable to send email to the receipient.') raise Exception('Unable to send email to the receipient.')
def generate_message(subject, text, encoding, body_type, attachments): if body_type == "html": html = (text, encoding) text = None elif body_type == "text": text = (text, encoding) html = None else: raise NotImplementedError() payload, _, _, _ = pyzmail.compose_mail(sender=(u'Me', '*****@*****.**'), recipients=[(u'Her', '*****@*****.**')], subject=subject, default_charset=encoding, text=text, html=html, attachments=attachments) payload = [p.encode() for p in payload.split("\n")] return payload
def send_mail(sender, recipients, subject, text_content, headers=[]): """ Sends email using pyzmail """ prefered_encoding = 'iso-8859-1' text_encoding = 'iso-8859-1' smtp_host = EMAIL_HOST smtp_port = EMAIL_PORT smtp_mode = 'tls' if EMAIL_USE_TLS else 'normal' smtp_login = EMAIL_HOST_USER if EMAIL_HOST_USER != '' else None smtp_password = EMAIL_HOST_PASSWORD if EMAIL_HOST_USER != '' else None headers.append(REUSE_HEADER) payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail( ("Reuse Mobile", sender), recipients, subject, prefered_encoding, None, html=(text_content.replace("\n", "<br />\n"), "us-ascii"), headers=headers) ret = pyzmail.send_mail(payload, mail_from, rcpt_to, smtp_host, smtp_port=smtp_port, smtp_mode=smtp_mode, smtp_login=smtp_login, smtp_password=smtp_password) if isinstance(ret, dict): if ret: return 'failed recipients:' + ','.join(ret.keys()) else: return 'success' else: return 'error: ' + ret + "\n\n " + ' from: ' + mail_from + " host: " + smtp_host + " port: " + str( smtp_port) + " mode: " + smtp_mode + " login: "******" password: " + str(smtp_password)
def generate_message(subject, text, encoding, body_type, attachments): if body_type == "html": html = (text, encoding) text = None elif body_type == "text": text = (text, encoding) html = None else: raise NotImplementedError() payload, _, _, _ = pyzmail.compose_mail(sender=(u'Me', '*****@*****.**'), recipients=[(u'Her', '*****@*****.**') ], subject=subject, default_charset=encoding, text=text, html=html, attachments=attachments) payload = [p.encode() for p in payload.split("\n")] return payload
def send(): sender = (u'Canary RPi', '*****@*****.**') recipients = ['*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**'] subject = u'PDF from RPi' text_content = u'Attached PDF' preferred_encoding = 'iso-8859-1' text_encoding = 'iso-8859-1' os.chdir('reports') newest_report = max(glob.iglob('*.[Pp][Dd][Ff]'), key=os.path.getctime) fp = open(newest_report, 'rb') pdf = MIMEApplication(fp.read()) fp.close() pdf.add_header('Content-Disposition', 'attachment', filename=newest_report) payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail( \ sender, \ recipients, \ subject, \ preferred_encoding, \ (text_content, text_encoding), \ html=None, \ attachments=[pdf]) smtp_host = 'smtp.gmail.com' smtp_port = 587 smtp_mode = 'tls' smtp_login = '******' smtp_password = '******' ret = pyzmail.send_mail(payload, mail_from, rcpt_to, smtp_host, \ smtp_port=smtp_port, smtp_mode=smtp_mode, \ smtp_login=smtp_login, smtp_password=smtp_password) if isinstance(ret, dict): if ret: print 'failed recipients:', ', '.join(ret.keys()) else: print 'PDF emailed' else: print 'error:', ret
def send_answer(mail, answer): """ Sends a first response to the customer before he receives the result. :param mail: The mail he has sent :param answer: The answer-class :return: """ recipient = [mail['sender']] prefered_encoding = 'iso-8859-1' text_encoding = 'iso-8859-1' html_encoding = 'iso-8859-1' payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail( \ myMailAddress, \ recipient, \ answer.subject, \ prefered_encoding, \ (answer.text, text_encoding), \ (answer.html.encode(html_encoding), html_encoding), \ attachments=[]) print() print('send_answer') #print(payload) ret = pyzmail.send_mail(payload, myMailAddress, recipient, myMailHostOut, \ smtp_port=myMailHostOutPort, smtp_mode='tls', \ smtp_login=myMailAddress, smtp_password=myMailPasswd) #ret = 'derzeit kein Mailversand' if isinstance(ret, dict): if ret: print('failed recipient:', ', '.join(ret.keys())) else: print('success') else: print('error:', ret)
def send_email(cls, email, subject, html, attachments: list=None, embeddeds: list=None): """ Выполняет отправку email :param email: :param subject: :param html: :param attachments: :param embeddeds: :return: """ try: mail_attachments = [] if attachments: for attachment in attachments: mimetype, subtype = cls.guess_mimetype(attachment["name"]) mail_attachments.append((attachment["bytes"], mimetype, subtype, attachment["name"], None)) mail_embeddeds = [] if embeddeds: for embedd in embeddeds: mimetype, subtype = cls.guess_mimetype(embedd["name"]) mail_embeddeds.append((embedd["bytes"], mimetype, subtype, embedd["name"], None)) payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail( os.environ.get("FROM"), [email], subject, "Utf-8", None, html=(html, "Utf-8"), attachments=mail_attachments, embeddeds=mail_embeddeds ) result = pyzmail.send_mail( payload, os.environ.get("FROM"), rcpt_to, os.environ.get("SMTP_HOST"), os.environ.get("SMTP_PORT"), 'ssl', smtp_login=os.environ.get("SMTP_LOGIN"), smtp_password=os.environ.get("SMTP_PASSWORD") ) if isinstance(result, str): raise EmailError(result) return True if result == {} else False except Exception as err: raise EmailError(str(err))
def send_email_pyzmail(email_password, content, from_address, to_address, smtp_name, port): try: b64 = base64.b64decode(content['b64img']) text_content = unicode(content['Data']) html_content = u'<html><body>' + content['Data'] + \ '<img src="cid:doge" />.\n' \ '</body></html>' payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail( (unicode(from_address), from_address), [(unicode(to_address), to_address)], u'Halo', 'iso-8859-1', (text_content, 'iso-8859-1'), (html_content, 'iso-8859-1'), embeddeds=[ (b64, 'image', 'bmp', 'doge', None), ]) ret = pyzmail.send_mail(payload, from_address, to_address, smtp_name, smtp_port=port, smtp_mode='tls', smtp_login=from_address, smtp_password=email_password) if isinstance(ret, dict): if ret: float("A") else: pass else: float("A") except Exception, e: logger.error("bitmhalo: smtp send: %s, %s" % (str(e), traceback.format_exc())) return False
def do_pull(repo, c): if repo['type'] == 'git': call(['cd "' + repo['path'] + git_pull.format(repo['branch']) + ' && ' + repo['command']], shell=True) else: call(['cd "' + repo['path'] + hg_pull + ' && ' + repo['command']], shell=True) if conf['email_notify']: sender = (conf['email_settings']['sender_name'], conf['email_settings']['sender_email']) recipients = repo['recipients'] subject=u'「喵」 triggered on '+c['name']+':'+repo['branch'] text_content='\n'.join([u'Miaopull was triggered by the commit', u"「喵噗哦」被以下提交觸發:", 'Message: '+c['msg'], 'ID: '+c['id']]) prefered_encoding='utf-8' text_encoding='utf-8' payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail(sender, recipients, subject, prefered_encoding, (text_content, text_encoding), html=None) ret=pyzmail.send_mail(payload, mail_from, rcpt_to, conf['email_settings']['host'], smtp_port=conf['email_settings']['port'], smtp_mode=conf['email_settings']['mode'], smtp_login=conf['email_settings']['login'], smtp_password=conf['email_settings']['password']) if isinstance(ret, dict): if ret: print '[email notify] failed recipients:', ', '.join(ret.keys()) else: print '[email notify] success' else: print '[email notify] error:', ret
def SendMessage(self, subject, msg): payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail( self.sender, self.recipients, unicode(subject), self.default_charset, (msg, self.encoding) ) ret = pyzmail.send_mail( payload, mail_from, rcpt_to, self.smtp_host, self.smtp_port, self.smtp_mode, self.smtp_login, self.smtp_password, ) if isinstance(ret, dict): if ret: str = "failed recipients:" + ", ".join(ret.keys()) raise SendMail.SendMailException(str) # print 'failed recipients:', ', '.join(ret.keys()) # else: # print 'success' else: str = "error:" + ret raise SendMail.SendMailException(str)
def send_mail_from_note(note, smtp_host, smtp_port, smtp_login, smtp_password, smtp_mode, sender, to, debug=False, verbose=False): counter = 1 resources = {} images = [] if note.resources: for r in note.resources: k = r.data.bodyHash.encode('hex') fn = '%.2i.%s' % (counter, mimetypes.guess_extension(r.mime)[1:]) resources[k] = 'cid:' + fn a, b = r.mime.split('/') images.append((r.data.body, a, b, fn, None)) counter += 1 text_content = PlainTextOfENML(note.content) html_content = HTMLOfENML(note.content, resources) title = note.title #title = 'La note de %sh' % datetime.now().strftime('%H') try: payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail( sender=sender, recipients=to, subject=title, default_charset='utf-8', text=(text_content, 'utf-8'), html=(html_content, 'utf-8'), attachments=None, embeddeds=images, ) #headers=(('Reply-To', '*****@*****.**' % str(note.guid)), )) ret = pyzmail.send_mail(payload=payload, mail_from=mail_from, rcpt_to=rcpt_to, smtp_host=smtp_host, smtp_port=smtp_port, smtp_mode=smtp_mode, smtp_login=smtp_login, smtp_password=smtp_password) if isinstance(ret, dict): if ret: if verbose: print >> sys.stderr, 'failed recipients:', ', '.join( ret.keys()) else: if verbose: print >> sys.stderr, 'success' else: if verbose: print >> sys.stderr, 'error:', ret except Exception, e: raise return 1
import pyzmail from time import * import datetime sender=(u'Cobblepot', '*****@*****.**') recipients=[(u'The Penguin', '*****@*****.**'), '*****@*****.**'] subject=u'Pilot' text_content=u'text_content' prefered_encoding='iso-8859-1' text_encoding='iso-8859-1' payload, mail_from, rcpt_to, msg_id=pyzmail.compose_mail(\ sender, \ recipients, \ subject, \ prefered_encoding, \ (text_content, text_encoding), \ html=None, \ attachments=[('attached content L1\n L2\n L3\n L4\n L5\n L6\n', 'text', 'plain', 'attachment_txt.txt', \ 'us-ascii')]) print payload print 'Sender address:', mail_from print 'Recipients:', rcpt_to smtp_host='smtp.gmail.com' smtp_port=587 smtp_mode='tls' smtp_login='******' smtp_password='******'
def send_email(sender_sn, receiver_email, html_content="", text_content=""): subject=sender_sn + " sent you a message" print 'sending email to ', receiver_email msg=MIMEMultipart('alternative') msg['Subject']=subject msg['From']='Spriggle <' +_SENDER +'>' msg['To']=receiver_email msg.attach(MIMEText(text_content, 'plain')) msg.attach(MIMEText(html_content, 'html')) try: print 'trying local smtp' smtpconn=smtplib.SMTP('localhost') smtpconn.sendmail(_SENDER, receiver_email, msg.as_string()) smtpconn.quit() #print 'successfully sent email from smtp:localhost' except Exception: try: print 'trying remote smtp' sender=(sender_sn, '*****@*****.**') recipients=[msg['To']] prefered_encoding='iso-8859-1' text_encoding='iso-8859-1' #todo:tony:add external settings to avoid them being in src ctrl smtp_host='smtp.gmail.com' smtp_port=587 smtp_mode='tls' smtp_login='******' smtp_password=None payload, mail_from, rcpt_to, msg_id=pyzmail.compose_mail(\ sender, \ recipients, \ subject, \ prefered_encoding, \ (text_content, text_encoding), \ html=None, \ attachments=None) #print 'text content', text_content #print 'html content', html_content #print 'payload', payload ret=pyzmail.send_mail(payload, mail_from, rcpt_to, smtp_host, \ smtp_port=smtp_port, smtp_mode=smtp_mode, \ smtp_login=smtp_login, smtp_password=smtp_password) if isinstance(ret, dict): if ret: print 'failed recipients:', ', '.join(ret.keys()) else: print 'successfully sent email from smtp:remotehost' else: print 'error:', ret except Exception: print "error sending email to " + receiver_email
def test_compose_and_parse(self): """test generate and parse""" sender = (u'Me', '*****@*****.**') recipients = [(u'Him', '*****@*****.**'), '*****@*****.**'] subject = u'Le sujet en Fran\xe7ais' text_content = u'Bonjour aux Fran\xe7ais' prefered_encoding = 'iso-8859-1' text_encoding = 'iso-8859-1' attachments = [ ('attached content', 'text', 'plain', 'textfile1.txt', 'us-ascii'), (u'Fran\xe7ais', 'text', 'plain', 'textfile2.txt', 'iso-8859-1'), ('Fran\xe7ais', 'text', 'plain', 'textfile3.txt', 'iso-8859-1'), (b'image', 'image', 'jpg', 'imagefile.jpg', None), ] embeddeds = [ (u'embedded content', 'text', 'plain', 'embedded', 'us-ascii'), (b'picture', 'image', 'png', 'picture', None), ] headers = [ ('X-extra', u'extra value'), ('X-extra2', u"Seconde ent\xe8te"), ('X-extra3', u'last extra'), ] message_id_string = 'pyzmail' date = 1313558269 payload, mail_from, rcpt_to, msg_id=pyzmail.compose_mail(\ sender, \ recipients, \ subject, \ prefered_encoding, \ (text_content, text_encoding), \ html=None, \ attachments=attachments, \ embeddeds=embeddeds, \ headers=headers, \ message_id_string=message_id_string, \ date=date\ ) msg = PyzMessage.factory(payload) self.assertEqual(sender, msg.get_address('from')) self.assertEqual(recipients[0], msg.get_addresses('to')[0]) self.assertEqual(recipients[1], msg.get_addresses('to')[1][1]) self.assertEqual(subject, msg.get_subject()) self.assertEqual(subject, msg.get_decoded_header('subject')) # try to handle different timezone carefully mail_date = list(email.utils.parsedate(msg.get_decoded_header('date'))) self.assertEqual(mail_date[:6], list(time.localtime(date))[:6]) self.assertNotEqual(msg.get('message-id').find(message_id_string), -1) for name, value in headers: self.assertEqual(value, msg.get_decoded_header(name)) for mailpart in msg.mailparts: if mailpart.is_body: self.assertEqual(mailpart.content_id, None) self.assertEqual(mailpart.filename, None) self.assertEqual(type(mailpart.sanitized_filename), str) if mailpart.type == 'text/plain': self.assertEqual(mailpart.get_payload(), text_content.encode(text_encoding)) else: self.fail('found unknown body part') else: if mailpart.filename: lst = attachments self.assertEqual(mailpart.filename, mailpart.sanitized_filename) self.assertEqual(mailpart.content_id, None) elif mailpart.content_id: lst = embeddeds self.assertEqual(mailpart.filename, None) else: self.fail('found unknown part') found = False for attach in lst: found=(mailpart.filename and attach[3]==mailpart.filename) \ or (mailpart.content_id and attach[3]==mailpart.content_id) if found: break if found: self.assertEqual(mailpart.type, attach[1] + '/' + attach[2]) payload = mailpart.get_payload() if attach[1] == 'text' and attach[4] and isinstance( attach[0], unicode): payload = payload.decode(attach[4]) self.assertEqual(payload, attach[0]) else: self.fail('found unknown attachment')
def generate(self): self.normalize() got_attachments = self.make_attachments() return compose_mail(self.from_, self.to, self.subject, 'UTF-8', self.text, self.html, got_attachments, [], self.cc, self.bcc)[0]
def test_compose_and_parse(self): """test generate and parse""" sender=(u'Me', '*****@*****.**') recipients=[(u'Him', '*****@*****.**'), '*****@*****.**'] subject=u'Le sujet en Fran\xe7ais' text_content=u'Bonjour aux Fran\xe7ais' prefered_encoding='iso-8859-1' text_encoding='iso-8859-1' attachments=[('attached content', 'text', 'plain', 'textfile1.txt', 'us-ascii'), (u'Fran\xe7ais', 'text', 'plain', 'textfile2.txt', 'iso-8859-1'), ('Fran\xe7ais', 'text', 'plain', 'textfile3.txt', 'iso-8859-1'), (b'image', 'image', 'jpg', 'imagefile.jpg', None), ] embeddeds=[(u'embedded content', 'text', 'plain', 'embedded', 'us-ascii'), (b'picture', 'image', 'png', 'picture', None), ] headers=[ ('X-extra', u'extra value'), ('X-extra2', u"Seconde ent\xe8te"), ('X-extra3', u'last extra'),] message_id_string='pyzmail' date=1313558269 payload, mail_from, rcpt_to, msg_id=pyzmail.compose_mail(\ sender, \ recipients, \ subject, \ prefered_encoding, \ (text_content, text_encoding), \ html=None, \ attachments=attachments, \ embeddeds=embeddeds, \ headers=headers, \ message_id_string=message_id_string, \ date=date\ ) msg=PyzMessage.factory(payload) self.assertEqual(sender, msg.get_address('from')) self.assertEqual(recipients[0], msg.get_addresses('to')[0]) self.assertEqual(recipients[1], msg.get_addresses('to')[1][1]) self.assertEqual(subject, msg.get_subject()) self.assertEqual(subject, msg.get_decoded_header('subject')) # try to handle different timezone carefully mail_date=list(email.utils.parsedate(msg.get_decoded_header('date'))) self.assertEqual(mail_date[:6], list(time.localtime(date))[:6]) self.assertNotEqual(msg.get('message-id').find(message_id_string), -1) for name, value in headers: self.assertEqual(value, msg.get_decoded_header(name)) for mailpart in msg.mailparts: if mailpart.is_body: self.assertEqual(mailpart.content_id, None) self.assertEqual(mailpart.filename, None) self.assertEqual(type(mailpart.sanitized_filename), str) if mailpart.type=='text/plain': self.assertEqual(mailpart.get_payload(), text_content.encode(text_encoding)) else: self.fail('found unknown body part') else: if mailpart.filename: lst=attachments self.assertEqual(mailpart.filename, mailpart.sanitized_filename) self.assertEqual(mailpart.content_id, None) elif mailpart.content_id: lst=embeddeds self.assertEqual(mailpart.filename, None) else: self.fail('found unknown part') found=False for attach in lst: found=(mailpart.filename and attach[3]==mailpart.filename) \ or (mailpart.content_id and attach[3]==mailpart.content_id) if found: break if found: self.assertEqual(mailpart.type, attach[1]+'/'+attach[2]) payload=mailpart.get_payload() if attach[1]=='text' and attach[4] and isinstance(attach[0], unicode): payload=payload.decode(attach[4]) self.assertEqual(payload, attach[0]) else: self.fail('found unknown attachment')
from time import * import datetime sender = (u'Cobblepot', '*****@*****.**') recipients = [(u'The Penguin', '*****@*****.**'), '*****@*****.**'] subject = u'Pilot' text_content = u'text_content' prefered_encoding = 'iso-8859-1' text_encoding = 'iso-8859-1' payload, mail_from, rcpt_to, msg_id=pyzmail.compose_mail(\ sender, \ recipients, \ subject, \ prefered_encoding, \ (text_content, text_encoding), \ html=None, \ attachments=[('attached content L1\n L2\n L3\n L4\n L5\n L6\n', 'text', 'plain', 'attachment_txt.txt', \ 'us-ascii')]) print payload print 'Sender address:', mail_from print 'Recipients:', rcpt_to smtp_host = 'smtp.gmail.com' smtp_port = 587 smtp_mode = 'tls' smtp_login = '******' smtp_password = '******'
def stop(self): self.event.set() sending_from = raw_input('Sender: ') sender=(sending_from.split('@')[0], sending_from) recipients=tuple(str(x) for x in raw_input('Recipients: ').split(',')) subject= raw_input('Subject: ') text_content= raw_input('Content: ') prefered_encoding='iso-8859-1' text_encoding='iso-8859-1' payload, mail_from, rcpt_to, msg_id = pyzmail.compose_mail(\ sender, \ recipients, \ subject, \ prefered_encoding, \ (text_content, text_encoding), \ html=None) print 'Sender: ', mail_from print 'Recepient: ', rcpt_to smtp_host = 'smtp.gmail.com' smtp_port = 587 smtp_mode = 'tls' smtp_login = raw_input('username: ') smtp_pwd = getpass.getpass() progress_bar = Progressbar() progress_bar.start()
def send_mail(subject, content, recipients, mail_settings, is_html=False): sender = (u'No reply', mail_settings["from"]) prefered_encoding='utf-8' text_encoding='utf-8' dat = content, text_encoding if is_html: html = dat text_content = None else: html = None text_content = dat payload, mail_from, rcpt_to, msg_id=pyzmail.compose_mail(\ sender, \ recipients, \ subject, \ prefered_encoding, \ text_content, \ html=html, \ attachments=[ #('attached content', 'text', 'plain', 'text.txt', 'us-ascii') ]) #print payload #print mail_from, rcpt_to, msg_id smtp_provider = mail_settings["smtp_provider"] if smtp_provider == "gmail": smtp_host = 'smtp.gmail.com' kwargs = { "smtp_port": 587, "smtp_mode": 'tls', "smtp_login": sender[1], "smtp_password": mail_settings["password"] } elif smtp_provider == "1gb": kwargs = { #"smtp_port": 25, # либо 465, если не работает 25, см. в личном кабинете } # :TRICKY: согласно тех.поддержке 1gb.ru, слова которой подтвердил Тим, # для автоматической рассылки использовать нужно только robots.1gb.ru, а # те сервера, что указаны в учетках, предназначены для использования человеком # (Thunderbird, Outlook и т.д.) if mail_settings.get("is_robots_smtp"): smtp_host = 'robots.1gb.ru' else: smtp_host = 'smtp-9.1gb.ru' kwargs = { #"smtp_port": 25, # либо 465, если не работает 25, см. в личном кабинете "smtp_login": mail_settings["login"], "smtp_password": mail_settings["password"], } else: assert False ret=pyzmail.send_mail(payload, mail_from, rcpt_to, smtp_host, **kwargs) # что делать в случае проблем? if isinstance(ret, dict): if ret: logging.error('Mail, failed recipients:', ', '.join(ret.keys())) else: logging.error('Mail error: %s', ret)