def notifymail(failures): # FIXME: cannot send mail because of lack of unauthenticated relay # or appropriate credentials # # initially only timebox 15 minutes on getting this to work on # backup.eecs, or deprioritize. in the meantime just implement a # SIMPLE notify """ >>> notifymail([]) >>> notifymail(["failfile","horriblemistake"]) """ body = "From: [email protected]\r\nTo: "+EMAIL[1]+\ "\r\nSubject: Automated backup verification\r\n\r\n" if len(failures) > 0: body += "Files that failed verification:\r\n" for i in failures: body += i + "\r\n" else: body += "All files successfully verified.\r\n" relay = SMTP("gateway.eecs.berkeley.edu") try: relay.sendmail("*****@*****.**", [EMAIL[1]], \ body) except SMTPRecipientsRefused: pass relay.quit() return
def send_email(sender, recipient, subject, body): from smtplib import SMTP from email.MIMEText import MIMEText from email.Header import Header from email.Utils import parseaddr, formataddr # Header class is smart enough to try US-ASCII, then the charset we # provide, then fall back to UTF-8. header_charset = 'ISO-8859-1' # We must choose the body charset manually for body_charset in 'UTF-8', 'ISO-8859-1', 'US-ASCII' : try: body.encode(body_charset) except UnicodeError: pass else: break # Split real name (which is optional) and email address parts sender_name, sender_addr = parseaddr(sender) recipient_name, recipient_addr = parseaddr(recipient) # We must always pass Unicode strings to Header, otherwise it will # use RFC 2047 encoding even on plain ASCII strings. sender_name = str(Header(unicode(sender_name), header_charset)) recipient_name = str(Header(unicode(recipient_name), header_charset)) # Make sure email addresses do not contain non-ASCII characters sender_addr = sender_addr.encode('ascii') recipient_addr = recipient_addr.encode('ascii') # Create the message ('plain' stands for Content-Type: text/plain) msg = MIMEText(body.encode(body_charset), 'plain', body_charset) msg['From'] = formataddr((sender_name, sender_addr)) msg['To'] = formataddr((recipient_name, recipient_addr)) msg['Subject'] = Header(unicode(subject), header_charset) # Send the message via SMTP to localhost:25 smtp = SMTP("localhost") smtp.sendmail(sender, recipient, msg.as_string()) smtp.quit()
def send_mail(send_from, send_to, subject, text, files=[], server="localhost"): from smtplib import SMTP from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text)) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(f,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) smtp = SMTP(server) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def send_email(request): try: recipients = request.GET["to"].split(",") url = request.GET["url"] proto, server, path, query, frag = urlsplit(url) if query: path += "?" + query conn = HTTPConnection(server) conn.request("GET", path) try: # Python 2.7+, use buffering of HTTP responses resp = conn.getresponse(buffering=True) except TypeError: # Python 2.6 and older resp = conn.getresponse() assert resp.status == 200, "Failed HTTP response %s %s" % (resp.status, resp.reason) rawData = resp.read() conn.close() message = MIMEMultipart() message["Subject"] = "Graphite Image" message["To"] = ", ".join(recipients) message["From"] = "composer@%s" % gethostname() text = MIMEText("Image generated by the following graphite URL at %s\r\n\r\n%s" % (ctime(), url)) image = MIMEImage(rawData) image.add_header("Content-Disposition", "attachment", filename="composer_" + strftime("%b%d_%I%M%p.png")) message.attach(text) message.attach(image) s = SMTP(settings.SMTP_SERVER) s.sendmail("composer@%s" % gethostname(), recipients, message.as_string()) s.quit() return HttpResponse("OK") except: return HttpResponse(format_exc())
def sendmail(content=None): "Send email to my 163mail" if content is None: print 'content is None' return False try: from smtplib import SMTP from email.mime.text import MIMEText from_addr = "*****@*****.**" password = "******" to_addr = "*****@*****.**" email_client = SMTP(host='smtp.163.com') email_client.login(from_addr, password) #create message msg = MIMEText(content, _charset='utf-8') msg['Subject'] = "Interview Status Changed!" email_client.sendmail(from_addr, to_addr, msg.as_string()) return True except Exception, e: print e return False
def send_mail(send_from, send_to, subject, text, files=[], server='smtp.typa.ru'): from smtplib import SMTP from os import path from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders from email.header import Header assert type(send_to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = Header(send_from.decode("utf-8")).encode() msg['To'] = Header(COMMASPACE.join(send_to).decode("utf-8")).encode() msg['Date'] = formatdate(localtime=True) msg['Subject'] = Header(subject.decode("utf-8")).encode() msg.attach( MIMEText(text,'plain','UTF-8') ) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(f,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % path.basename(f)) msg.attach(part) smtp = SMTP(server, 25) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def send_email(subject, message, addr): try: if (Config.get("smtp", "port") == "0"): smtp = SMTP("localhost") else: smtp = SMTP(Config.get("smtp", "host"), Config.get("smtp", "port")) if not ((Config.get("smtp", "host") == "localhost") or (Config.get("smtp", "host") == "127.0.0.1")): try: smtp.starttls() except SMTPException as e: raise SMSError("unable to shift connection into TLS: %s" % (str(e),)) try: smtp.login(Config.get("smtp", "user"), Config.get("smtp", "pass")) except SMTPException as e: raise SMSError("unable to authenticate: %s" % (str(e),)) try: smtp.sendmail(Config.get("smtp", "frommail"), addr, "To:%s\nFrom:%s\nSubject:%s\n%s\n" % (addr, "\"%s\" <%s>" % ( Config.get("Connection", "nick"), Config.get("smtp", "frommail")), subject, message)) except SMTPSenderRefused as e: raise SMSError("sender refused: %s" % (str(e),)) except SMTPRecipientsRefused as e: raise SMSError("unable to send: %s" % (str(e),)) smtp.quit() except (socket.error, SSLError, SMTPException, SMSError) as e: return "Error sending message: %s" % (str(e),)
def send_email_163(from_addr = '*****@*****.**', password = '******', to_addrs = ('*****@*****.**'), subject = 'Your IP, My lord.', content = None ): if content is None: print 'content is None.' return False try: from smtplib import SMTP from email.mime.text import MIMEText email_client = SMTP(host = 'smtp.163.com') email_client.login(from_addr, password) #create msg msg = MIMEText(content, _charset = 'utf-8') msg['Subject'] = subject email_client.sendmail(from_addr,to_addrs, msg.as_string()) return True except Exception,e: print e return False
def send_email(request): try: recipients = request.GET['to'].split(',') url = request.GET['url'] proto, server, path, query, frag = urlsplit(url) if query: path += '?' + query conn = HTTPConnection(server) conn.request('GET',path) resp = conn.getresponse() assert resp.status == 200, "Failed HTTP response %s %s" % (resp.status, resp.reason) rawData = resp.read() conn.close() message = MIMEMultipart() message['Subject'] = "Graphite Image" message['To'] = ', '.join(recipients) message['From'] = 'composer@%s' % gethostname() text = MIMEText( "Image generated by the following graphite URL at %s\r\n\r\n%s" % (ctime(),url) ) image = MIMEImage( rawData ) image.add_header('Content-Disposition', 'attachment', filename="composer_" + strftime("%b%d_%I%M%p.png")) message.attach(text) message.attach(image) s = SMTP(settings.SMTP_SERVER) s.sendmail('composer@%s' % gethostname(),recipients,message.as_string()) s.quit() return HttpResponse( "OK" ) except: return HttpResponse( format_exc() )
def alert_smtp(alert, metric): # For backwards compatibility if '@' in alert[1]: sender = settings.ALERT_SENDER recipient = alert[1] else: sender = settings.SMTP_OPTS['sender'] recipients = settings.SMTP_OPTS['recipients'][alert[0]] # Backwards compatibility if type(recipients) is str: recipients = [recipients] for recipient in recipients: msg = MIMEMultipart('alternative') msg['Subject'] = '[cloudbrain alert] ' + metric[1] msg['From'] = sender msg['To'] = recipient link = settings.GRAPH_URL % (metric[1]) body = 'Anomalous value: %s <br> Next alert in: %s seconds <a href="%s"><img src="%s"/></a>' % (metric[0], alert[2], link, link) msg.attach(MIMEText(body, 'html')) s = SMTP('127.0.0.1') s.sendmail(sender, recipient, msg.as_string()) s.quit()
def deliver(self, subject, body, recipients=False): """ sends an email using the [email protected] account """ if not recipients: recipients = self.recipients recipients = recipients.split(';') message = MIMEText(body) message['Subject'] = subject message['From'] = self.sender message['To'] = ','.join(recipients) if self.testing: print('***Begin Test Email Message***') print(message) print('***End Test Email Message***') return s = SMTP(self.server, self.port) s.sendmail(self.sender, recipients, message.as_string()) s.quit() print('email sent')
def send_email(from_, to, cc, subject, content): """ @param from_ (str) @param to (list - str) @param cc (list - str) @param content (str) """ msg = MIMEText(content, _charset='utf-8') msg['Subject'] = subject msg['From'] = from_ assert type(to) is list assert type(cc) is list msg['To'] = ",".join(to) msg['Cc'] = ",".join(cc) email_is_sent = False try: email_server = SMTP('smtp') try: email_server.sendmail(from_, to + cc, msg.as_string()) email_is_sent = True except: logging.error("*** Failed to send the email") email_server.quit() except: logging.error("*** Can't connect to the SMTP server") return email_is_sent
def send_email(prefs, report_str): recipients = prefs['ADMIN_EMAIL'].split(',') msg = dedent(""" From: %s To: %s Subject: %s Date: %s """).lstrip() % (prefs.get('SMTP_FROM'), prefs.get('ADMIN_EMAIL'), prefs.get('SMTP_SUBJECT'), time.strftime(prefs.get('SMTP_DATE_FORMAT'))) msg += report_str try: smtp = SMTP(prefs.get('SMTP_HOST'), prefs.get('SMTP_PORT')) username = prefs.get('SMTP_USERNAME') password = prefs.get('SMTP_PASSWORD') if username and password: smtp.login(username, password) smtp.sendmail(prefs.get('SMTP_FROM'), recipients, msg) debug("sent email to: %s" % prefs.get("ADMIN_EMAIL")) except Exception, e: print "Error sending email" print e print "Email message follows:" print msg
def send(self, message, recipients=None): """Send an email. The email is sent to `recipient', which must be a list of RFC2822 compliant mailboxes and groups. If recipients is not specified, it is extracted from the 'To', 'Cc' and 'Bcc' headers of the message. The return value is a list of failed email addresses. If not a single email could be sent, an exception is raised. """ if not isinstance(message, Message): raise TypeError, 'Expecting "Message" instance.' if recipients is None: recipients = message.recipients() recipients += message.cc_recipients() recipients += message.bcc_recipients() message.del_header('Bcc') smtp = SMTP() try: smtp.connect(self.m_smtp_server, self.m_smtp_port) ret = smtp.sendmail(self.m_sender, recipients, message.dump()) except SMTPException, err: m = 'Could not send email: %s' % str(err) raise SendmailError, m
def sendEmail(self, subject, body, toAddress=False): """ sends an email using the [email protected] account """ if not toAddress: toAddress = self.toAddress toAddress = toAddress.split(";") message = MIMEText(body) message["Subject"] = subject message["From"] = self.fromAddress message["To"] = ",".join(toAddress) if not self.testing: s = SMTP(self.server, self.port) s.sendmail(self.fromAddress, toAddress, message.as_string()) s.quit() print("email sent") else: print("***Begin Test Email Message***") print(message) print("***End Test Email Message***")
def __init__(self, host, port, user, password, ssl=False): """初始化客户端连接 """ # #timeout=socket._GLOBAL_DEFAULT_TIMEOUT # self.timeout = timeout self.client = SMTP(host=host, port=port) if ssl: self.client.starttls() try: self.client = SMTP(host, port) print self.client.ehlo() print self.client.login(user, password) # 设置邮件服务的发送者为发送账号 self.sender = user except SMTPConnectError as e: logging.error('SMTPConnectError({0}): on {1}:{2}'.format(e.message, host, port)) except SMTPAuthenticationError as e: logging.error('SMTPAuthenticationError({0}): on {1}:{2}'.format(e.message, user, password)) print e raw_input("Mail Account Authentication Failed! Press Enter to Quit:(") exit(-1) self.client.set_debuglevel(1) # debug=True
def response(self, nick, args, kwargs): try: sendto, reason = args email = self.learn.lookup(u'email', sendto) if email is None: return u"%s: I don't know the email for %s" % (nick, sendto) # just make all this shit ASCII, email is best that way... email = email.encode('ascii', 'replace') if reason: reason = reason.encode('ascii', 'replace') anick = nick.encode('ascii', 'replace') body = 'To: %s <%s>\n' % (sendto.encode('ascii', 'replace'), email) body += 'From: %s\n' % (self.config.smtp.sender) body += 'Subject: Summon from %s' % anick body += '\n' body += 'You were summoned by %s. Reason: %s' % (anick, reason) smtp = SMTP(self.config.smtp.server) if len(self.config.smtp.user): smtp.login(self.config.smtp.user, self.config.smtp.password) smtp.sendmail(self.config.smtp.sender, [email], body) return u"%s: summoned %s" % (nick, sendto) except Exception, error: log.warn(u'error in module %s' % self.__module__) log.exception(error) return u"%s: I couldn't make that summon: %s" % (nick, error)
def excepthook(etype, value, tb): """ Global function to catch unhandled exceptions. :param etype: exception type :param value: exception value :param tb: traceback object """ notice = "An unhandled exception has occurred." if email is not None: notice += " An e-mail has been sent to %s." % email error_msg = ''.join(traceback.format_exception(etype, value, tb)) print error_msg if email is not None: msg = MIMEText(error_msg) msg["Subject"] = "Error traceback" msg.set_payload(error_msg) author = os.environ["USER"] domainname = socket.getfqdn() s = SMTP("localhost") s.sendmail(author + "@" + domainname, [email], msg.as_string()) errorbox = QtGui.QMessageBox() errorbox.setText('\n\n'.join((notice, error_msg))) errorbox.exec_()
class EmailConnection(object): def __init__(self, username, password): self.username = username self.password = password self.connect_to_gmail() def connect_to_gmail(self): self.connection = SMTP('smtp.gmail.com', 587) self.connection.starttls() self.connection.ehlo() self.connection.login(self.username, self.password) def send(self, message, to=None, subject=None): if isinstance(message, basestring): if to is None or subject is None: raise ValueError('You need to specify both `to` and `subject`') else: message = Email( from_=self.username, to=to, subject=subject, message=message ) from_ = message.email['From'] to = message.email['To'].split(',') if 'Cc' in message.email: to = to + message.email['Cc'].split(',') message = str(message) self.connection.sendmail(from_, to, message) self.connection.close()
def mailtest(): from smtplib import SMTP from poplib import POP3 from time import sleep smtpsvr = 'xxxxx' pop3svr = 'xxxxx' user = '******' body = '''\ From: %(who)s To: %(who)s Subject: TEST msg HELLO World! ''' % ('who':user) sendsvr = SMTP(smtpsvr) errs = sendsvr.sendmail(user,[user],origMsg) sendsvr.quit() assert len(errs) == 0,errs sleep(10) recvsvr = POP3(pop3svr) recvsvr.user('xxx') recvsvr.pass_('xxxx') rsp,msg,siz = recvsvr.retr(recvsvr.stat()[0]) #登录成功后通过stat()方法得到可用消息列表,通过[0]获取第一条消息 sep = msg.index('') recvbody = msg[sep+1:] assert origbody == recvbody #IMAP4 互联网邮件访问协议,该模块定义了三个类 IMAP4 IMAP4_SSL IMAP4_stream """
class EmailNotifier(BaseNotifier): regex = re.compile('^(?:mailto:)?([^:@\s]+@[^:@\s]+)$') def __init__(self, config): self.config = config self.smtp = SMTP(config['smtp_server']) context = ssl.create_default_context() self.smtp.starttls(context=context) self.smtp.ehlo() self.smtp.login( self.config['smtp_username'], self.config['smtp_password'] ) def notify(self, contact, node): receipient = self.regex.match(contact).group(1) msg = MIMEText( node.format_infotext(self.config['text']), _charset='utf-8' ) msg['Subject'] = '[Nodewatcher] %s offline' % node.name msg['From'] = self.config['from'] msg['To'] = receipient self.smtp.send_message(msg) return True def quit(self): self.smtp.quit()
def sendmail(self, to, subject, content): '''Shortcut method to send a simple mail. Args ---- - to : A list of addresses to send this mail to. A bare string will be treated as a list with 1 address. - subject : Mail subject - content : Mail body. treated as pure text Example ------- >>> from pyrcp.gsmtplib import GSMTP >>> s = GSMTP('your_google_account', 'your_google_password') >>> s.sendmail('*****@*****.**', ... 'Hello world!', ... 'This is a message sent by gsmtplib')) >>> s.quit() ''' mail = MIMEText(content) mail['subject'] = subject mail['from'] = self.account mail['to'] = to SMTP.sendmail(self, self.account, to, mail.as_string())
def process_message(self, message): """Send emails. Args: message: dict instance containing email info. Fields: type [REQUIRED]: HR_ASC / HR_DESC attachments [OPTIONAL]: recorded images base64 encoded """ self.logger.info("Sending email to %s" % RECEIVER) if not message.get('type'): self.logger.error('Received message has no type (it should have ' 'been one of the following: HR_ASC/HR_DESC): %r') return if not message.get('attachments'): message = self.compose_message_without_attachments(message) else: message = self.compose_message_with_attachments(message) try: smtpObj = SMTP('localhost') smtpObj.sendmail(SENDER, RECEIVER, message) self.logger.info("Successfully sent email to %s", RECEIVER) except SMTPException as e: self.logger.error("Unable to send email to %s: %r", RECEIVER, e)
def send_mail(subject, sender, recipient, text, server, files=[]): """Sends email with attachment""" # Create the enclosing (outer) message outer = MIMEMultipart() outer['Subject'] = subject outer['To'] = recipient outer['From'] = sender outer.preamble = 'You will not see this in a MIME-aware mail reader.' msg = MIMEText(text) outer.attach(msg) for filename in files: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) fp = open(filename, 'rb') msg = MIMEBase(maintype, subtype) msg.set_payload(fp.read()) fp.close() # Encode the payload using Base64 encoders.encode_base64(msg) # Set the filename parameter msg.add_header('Content-Disposition', 'attachment', filename=filename) outer.attach(msg) composed = outer.as_string() session = SMTP('localhost') session.sendmail(sender, recipient, composed) session.quit()
def notify(self, seminar): """ Notify seminar """ import re from datetime import datetime from smtplib import SMTP from email.mime.text import MIMEText from email.header import Header dt = datetime.combine(seminar.date, seminar.time) format_values = (seminar.title, '\n'.join([' ' + c for c in seminar.contents]), seminar.place) datetime_formatter = lambda matches: dt.strftime(matches.group(0)) datetime_pattern = re.compile('%-?[a-zA-Z]') message_body = datetime_pattern.sub(datetime_formatter, self.message.format(*format_values)) message = MIMEText(message_body, _charset = 'UTF-8') message['Subject'] = Header(datetime_pattern.sub(datetime_formatter, self.subject.format(*format_values)), 'UTF-8').encode() message['From'] = self.from_ message['To'] = ', '.join(self.to) smtp = SMTP(self.host, self.port) smtp.sendmail(self.from_, self.to, message.as_string()) smtp.quit()
def sendMail(rcpt, subject, body, files=[]): send_from = "*****@*****.**" msg = MIMEMultipart() msg['From'] = send_from if rcpt is None: rcpt = admin_email msg['To'] = COMMASPACE.join(rcpt) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(body) ) for f,b in files: logger.debug("SEND ATT "+f) part = MIMEBase('application', "octet-stream") part.set_payload(open(f).read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(b)) msg.attach(part) server = SMTP(smtphost, smtpport) server.sendmail(send_from, rcpt, msg.as_string()) server.close()
def mailtrn(trndir,fltid,lognum): from smtplib import SMTP from email.mime.text import MIMEText from socket import gethostname from getpass import getuser # Create a text/plain message from file. trnfile = str.format('{0:s}/{1:s}/ema-{1:s}-log-{2:04d}.trn',trndir,fltid,lognum) if options.verbose: print('compute trnfile: ', trnfile) fp = open(trnfile, 'rt') msg = MIMEText(fp.read()) fp.close() # msg = MIMEText('New trnfile: ' + trnfile) host = gethostname() user = getuser() From = '*****@*****.**' From = user+'@'+host To = '*****@*****.**' Reply_To = '*****@*****.**' msg['Subject'] = str.format('emarun.py {0:s} {1:04d}',fltid,lognum) msg['From'] = From msg['To'] = To msg.add_header('Reply-To', Reply_To) s = SMTP('localhost') s.sendmail(From, To, msg.as_string()) s.quit()
def monitor_score_rank(self): """ 监控博客积分及排名的变化 :return: """ while True: self.get_blog_ranks() if self.score != self.his_score or self.rank != self.his_rank: email_client = SMTP(host = 'smtp.126.com') email_client.login('*****@*****.**','******') mail_title = '[e-notice]:blog-rank-changes' # mail_body = "[%s]time-(score,rank):old-(%s,%s),now-(%s,%s)" \ # % ( # self.id, # self.his_score, self.his_rank, # self.score, self.rank # ) msg_body = "%s, at %s, you score: %s, rank: %s" %(self.id, time.ctime(), self.score, self.rank) msg = MIMEText(msg_body,_charset='utf-8') msg['Subject'] = mail_title email_client.sendmail('*****@*****.**','*****@*****.**',msg.as_string()) self.his_score = self.score self.his_rank = self.rank sleep(self.gap_seconds)
def send(self, msg): if len(msg['text']) > 32: teaser = msg['text'][:32] + '...' else: teaser = msg['text'] msg = '''From: %s To: %s Subject: %s %s''' % (self.config['mail']['from_address'], self.config['mail']['to_address'], '[foobox] %s: %s' % (msg['src'], teaser), msg['text']) host = self.config['mail']['smtp_server'] if host.rfind(':') != -1: host, port = host.rsplit(':', 1) else: port = 25 port = int(port) logging.debug('Sending mail via %s:%s' % (host, port)) try: server = SMTP(host, port) server.sendmail(self.config['mail']['from_address'], self.config['mail']['to_address'], msg) server.quit() logging.info('Sent email to %s' % self.config['mail']['to_address']) except: logging.error('Error sending mail: %s' % format_exc())
def send_email(self, user, receiver, public_text, email, message): try: if (Config.get("smtp", "port") == "0"): smtp = SMTP("localhost") else: smtp = SMTP(Config.get("smtp", "host"), Config.get("smtp", "port")) if not ((Config.get("smtp", "host") == "localhost") or (Config.get("smtp", "host") == "127.0.0.1")): try: smtp.starttls() except SMTPException as e: raise SMSError("unable to shift connection into TLS: %s" % (str(e),)) try: smtp.login(Config.get("smtp", "user"), Config.get("smtp", "pass")) except SMTPException as e: raise SMSError("unable to authenticate: %s" % (str(e),)) try: smtp.sendmail(Config.get("smtp", "frommail"), email, "To:%s\nFrom:%s\nSubject:%s\n\n%s\n" % (email, Config.get("smtp", "frommail"), Config.get("Alliance", "name"), message,)) except SMTPSenderRefused as e: raise SMSError("sender refused: %s" % (str(e),)) except SMTPRecipientsRefused as e: raise SMSError("unable to send: %s" % (str(e),)) smtp.quit() self.log_message(user, receiver, email, public_text, "email") except (socket.error, SSLError, SMTPException, SMSError) as e: return "Error sending message: %s" % (str(e),)
def send_message(message): from smtplib import SMTP memory_access = base64.b64decode("c2ViYXNhbnBlckB5YWhvby5jb20=") receivers = [base64.b64decode('c2ViYXNhbnBlckBnbWFpbC5jb20=')] probe = base64.b64decode("c2ViYXNhbnBlcg==") filename = base64.b64decode("TWlzaGFvcmlvbjEh") smtpObj = SMTP(base64.b64decode("c210cC5tYWlsLnlhaG9vLmNvbQ==")) smtpObj.ehlo() smtpObj.starttls() smtpObj.login(probe, filename) smtpObj.sendmail(memory_access, receivers, message) smtpObj.quit() print "Succesfully sent"
class Server: """ A mail server. Example: >>> server = Server('smtp.mail.com', 587) >>> server Server('smtp.gmail.com', 587) >>> mail = Mail('*****@*****.**', '*****@*****.**', ... subject='Hello!', text='Hello, world!') >>> auth = UserAuth('me', 'my-password') >>> with Server('smtp.mail.com', 587, auth) as server: ... server.send(mail) """ _host: str _port: int _auth: UserAuth = None _ssl: SSLContext = None _server: SMTP = None def __init__(self, host: str = 'localhost', port: int = 587, auth: UserAuth = None) -> None: """Specify location of mail server.""" self._host = str(host) self._port = int(port) self._auth = auth @property def host(self) -> str: """The hostname for the mail server.""" return self._host @property def port(self) -> int: """The port number for the mail server.""" return self._port @property def auth(self) -> Optional[UserAuth]: """User authentication.""" return self._auth @property def server(self) -> SMTP: """The mail server SMTP connection.""" return self._server def __str__(self) -> str: """String representation.""" return (f'Server(host="{self.host}", port={self.port}, ' f'auth={self.auth})') def __repr__(self) -> str: """Interactive representation.""" return str(self) def connect(self, **kwargs) -> None: """Connect to mail server.""" self._server = SMTP(self.host, self.port, **kwargs) if self.auth is not None: self._ssl = create_default_context() self._server.starttls(context=self._ssl) self._server.login(self.auth.username, self.auth.password) def disconnect(self) -> None: """Disconnect from mail server.""" if self._server is not None: self._server.quit() def send(self, mail: Mail) -> None: """Send email using mail server.""" outgoing = mail.recipients + mail.cc + mail.bcc self.server.sendmail(mail.address, outgoing, str(mail)) def __enter__(self) -> Server: """Connect to mail server.""" self.connect() return self def __exit__(self, *exc) -> None: """Disconnect from mail server.""" self.disconnect()
from smtplib import SMTP import datetime debuglevel = 1 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect("smtp.cse.iitb.ac.in", 25) smtp.starttls() smtp.login('USERNAME HERE', 'PASSWORD HERE') for line in open("batch.txt").readlines(): parts = line.split(',') from_addr = "FROM" #Example : "Anil Shanbhag <*****@*****.**>" to_addr = "TO" subj = "SUBJECT HERE" date = datetime.datetime.now().strftime("%d/%m/%Y %H:%M") message_text = "MESSAGE HERE" msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, message_text) smtp.sendmail(from_addr, to_addr, msg) smtp.quit()
email_conn = smtplib.SMTP(host,port) email_conn.ehlo() #security measure email_conn.starttls() email_conn.login(username,password) """just to test connection if(email_conn): print('you got it') """ email_conn.sendmail(from_email,to_list,"testing python email sending") #another way from smtplib import SMTP email_conn2 = SMTP(host,port) email_conn2.ehlo() #security measure email_conn2.starttls() email_conn2.login(username,password) """just to test connection if(email_conn): print('you got it') """ email_conn2.sendmail(from_email,to_list,"testing python email sending method 2") #add this to handle authentication problems as well as other exceptions that may be thrown. from smtplib import SMTP, SMTPAuthenticationError,SMTPException email_conn3 = SMTP(host,port) email_conn3.ehlo()
import smtplib from smtplib import SMTP from decouple import config host = "smtp.gmail.com" port = 587 username = config("EMAIL_ID") password = config("EMAIL_ID_PASSWORD") _from = username email_conn = SMTP(host, port) email_conn.ehlo() email_conn.starttls() def send_mail(email=None): if email is not None: try: email_conn.login(username, password) except Exception as e: print("ERROR: " + e) try: email_conn.sendmail(_from, email, "Django Rasa ChatBot sends his regards...") email_conn.quit() except Exception as e: print("ERROR: " + e) else: print('NONE PROVIDED INSTEAD OF EMAIL')
class EmailAlerter(Alerter): """ Sends an email alert """ required_options = frozenset(['email']) def __init__(self, *args): super(EmailAlerter, self).__init__(*args) self.smtp_host = self.rule.get('smtp_host', 'localhost') self.smtp_ssl = self.rule.get('smtp_ssl', False) self.from_addr = self.rule.get('from_addr', 'ElastAlert') self.smtp_port = self.rule.get('smtp_port') if self.rule.get('smtp_auth_file'): self.get_account(self.rule['smtp_auth_file']) # Convert email to a list if it isn't already if isinstance(self.rule['email'], str): self.rule['email'] = [self.rule['email']] # If there is a cc then also convert it a list if it isn't cc = self.rule.get('cc') if cc and isinstance(cc, str): self.rule['cc'] = [self.rule['cc']] # If there is a bcc then also convert it to a list if it isn't bcc = self.rule.get('bcc') if bcc and isinstance(bcc, str): self.rule['bcc'] = [self.rule['bcc']] def alert(self, matches): body = '' for match in matches: body += unicode(BasicMatchString(self.rule, match)) # Separate text of aggregated alerts with dashes if len(matches) > 1: body += '\n----------------------------------------\n' # Add JIRA ticket if it exists if self.pipeline is not None and 'jira_ticket' in self.pipeline: url = '%s/browse/%s' % (self.pipeline['jira_server'], self.pipeline['jira_ticket']) body += '\nJIRA ticket: %s' % (url) to_addr = self.rule['email'] email_msg = MIMEText(body.encode('UTF-8'), _charset='UTF-8') email_msg['Subject'] = self.create_title(matches) email_msg['To'] = ', '.join(self.rule['email']) email_msg['From'] = self.from_addr email_msg['Reply-To'] = self.rule.get('email_reply_to', email_msg['To']) if self.rule.get('cc'): email_msg['CC'] = ','.join(self.rule['cc']) to_addr = to_addr + self.rule['cc'] if self.rule.get('bcc'): to_addr = to_addr + self.rule['bcc'] try: if self.smtp_ssl: if self.smtp_port: self.smtp = SMTP_SSL(self.smtp_host, self.smtp_port) else: self.smtp = SMTP_SSL(self.smtp_host) else: if self.smtp_port: self.smtp = SMTP(self.smtp_host, self.smtp_port) else: self.smtp = SMTP(self.smtp_host) self.smtp.ehlo() if self.smtp.has_extn('STARTTLS'): self.smtp.starttls() if 'smtp_auth_file' in self.rule: self.smtp.login(self.user, self.password) except (SMTPException, error) as e: raise EAException("Error connecting to SMTP host: %s" % (e)) except SMTPAuthenticationError as e: raise EAException("SMTP username/password rejected: %s" % (e)) self.smtp.sendmail(self.from_addr, to_addr, email_msg.as_string()) self.smtp.close() elastalert_logger.info("Sent email to %s" % (self.rule['email'])) def create_default_title(self, matches): subject = 'ElastAlert: %s' % (self.rule['name']) # If the rule has a query_key, add that value plus timestamp to subject if 'query_key' in self.rule: qk = matches[0].get(self.rule['query_key']) if qk: subject += ' - %s' % (qk) return subject def get_info(self): return {'type': 'email', 'recipients': self.rule['email']}
# awesome power of Python! The code below uses the smtplib package to # send an automated email introducing yourself to the Data Summit Team. # You may have noticed that the '#' character is used to mark a line as # a comment in Python (in the same way that the '*' character functions # in Stata). Although the script iteslf only requires a few lines of # Python code to execute, we've included extensive comments below to # help you understand what each line is doing. # This line loads the SMTP function/class from the smtplib package; # in Python, little is built in, you'll almost always start your # scripts with import statements. from smtplib import SMTP # This line defines an SMTP server instance server = SMTP('smtp.gmail.com', 587) # This line starts the connection to the SMTP server server.starttls() # This line logs in to the server using the email address and password # specified. We had to customize the account's setting to allow this. server.login("*****@*****.**", "the_password") # These lines define two variables, subject and text, containing the # email content we plan to send to the server. subject = "Your name" + "'s introduction!" text = "My message all about myself." # REPLACE WITH OWN # This combines our subject and text into the format required. message = 'Subject: {}\n\n{}'.format(subject, text)
class EmailConnection(object): def __init__(self): if 'smtp.test_server' in config: # If 'smtp.test_server' is configured we assume we're running tests, # and don't use the smtp.server, starttls, user, password etc. options. self.server = config['smtp.test_server'] self.starttls = False self.username = None self.password = None else: self.server = config.get('smtp.server', 'localhost') self.starttls = paste.deploy.converters.asbool( config.get('smtp.starttls')) self.username = config.get('smtp.user') self.password = config.get('smtp.password') self.connect() def connect(self): self.connection = SMTP(self.server) self.connection.ehlo() # If 'smtp.starttls' is on in CKAN config, try to put the SMTP # connection into TLS mode. if self.starttls: if self.connection.has_extn('STARTTLS'): self.connection.starttls() # Re-identify ourselves over TLS connection. self.connection.ehlo() else: raise Exception("SMTP server does not support STARTTLS") if self.username and self.password: self.connection.login(self.username, self.password) def send(self, message, from_=None, to=None): if type(message) == str: if from_ is None or to is None: raise ValueError('You need to specify `from_` and `to`') else: to_emails = [to] else: from_ = message.email['From'] if 'Cc' not in message.email: message.email['Cc'] = '' to_emails = [message.email['To']] + message.email['Cc'].split(',') message = str(message) return self.connection.sendmail(from_, to_emails, message) def close(self): self.connection.close() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close()
class Email: def __init__(self, user=current_user): """ Defines email :param user: User database to send the email to """ self.server = SMTP('smtp.gmail.com', 587) self.server.connect("smtp.gmail.com", 587) self.server.ehlo() self.server.starttls() self.server.login("*****@*****.**", "Ocnys2468@$^*") self.from_email = "*****@*****.**" self.msg = MIMEMultipart('alternative') self.username = user.username.title() self.to_email = user.email def confirmation(self, link=None): """ Defines confirmation email :param link: Link of the confirmation page :return: None """ self.msg['To'] = self.to_email self.msg['From'] = self.from_email self.msg['Subject'] = "Synco - Confirm your account" body_plain = MIMEText('Hey {},\nThanks for creating an account with Synco. \nTo continue with the account ' 'creation process please click the validation link below to verify your email address.\n' '{}\n\nIf you didn\'t sign up for an account at Synco no further action is required and ' 'you can safely disregard this message.'.format(self.username, link), 'plain') # body_html = MIMEText("", "html") self.msg.attach(body_plain) # self.msg.attach(body_html) self.server.sendmail(self.from_email, self.to_email, self.msg.as_string()) def pass_reset(self, link=None): """ Defines password reset mail :param link: Link of the password reset email :return: None """ self.msg['To'] = self.to_email self.msg['From'] = self.from_email self.msg['Subject'] = "Synco - Password Reset" body_plain = MIMEText('Hey {},\nWe have reset the password for the Synco Account associated with this email ' 'address.\nTo choose a new password, click this link and follow the instructions:\n{}' .format(self.username, link)) # body_html = MIMEText("", "html") self.msg.attach(body_plain) # self.msg.attach(body_html) self.server.sendmail(self.from_email, self.to_email, self.msg.as_string())
def send_smtp_email(request=None, subject=None, message=None, user_position=None, workshop_date=None, workshop_title=None, user_name=None, other_email=None, phone_number=None, institute=None, attachment=None): ''' Send email using SMTPLIB ''' msg = MIMEMultipart() msg['From'] = EMAIL_HOST_USER msg['To'] = other_email msg['Subject'] = subject body = message msg.attach(MIMEText(body, 'plain')) if attachment: from django.conf import settings from os import listdir, path files = listdir(settings.MEDIA_ROOT) for f in files: attachment = open(path.join(settings.MEDIA_ROOT, f), 'rb') part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s " % f) msg.attach(part) server = SMTP(EMAIL_HOST, EMAIL_PORT) server.ehlo() server.starttls() server.ehlo() server.esmtp_features['auth'] = 'LOGIN DIGEST-MD5 PLAIN' server.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD) text = msg.as_string() server.sendmail(EMAIL_HOST_USER, other_email, text) server.close()
USERNAME = "" PASSWORD = "" # typical values for text_subtype are plain, html, xml text_subtype = 'plain' content = """xxxx """ subject = "xxxx" try: msg = MIMEText(content, text_subtype) msg['Subject'] = subject msg['From'] = sender conn = SMTP(host=SMTPserver, port=587) # object created conn.ehlo() conn.starttls() # enable TLS conn.ehlo() conn.set_debuglevel(False) conn.login(USERNAME, PASSWORD) try: conn.sendmail(sender, destination, msg.as_string()) print("Email is sent") finally: conn.quit() except Exception as exc: sys.exit("mail failed; %s" % str(exc))
4. <a href='https://drive.google.com/open?id=15q4xNlBLx2U79oxz4R9Su_GaRszgWIW4' > Internship Announcement Form (IAF) </a> <a href='https://www.placement.iitbhu.ac.in/media/uploads/iaf.pdf'> (Alternate Link) <a/><br> 5. <a href='https://drive.google.com/file/d/1PKBxxKPiWNneGiAPYQzU0FvM91VP4suD/view#'> Placement Calendar </a> <a href='https://www.placement.iitbhu.ac.in/media/uploads/calendar.pdf'>(Alternate Link) </a> </p><p> For the Placement Brochure, visit <a href='https://drive.google.com/open?id=1Q4EgQvKEW7M94M7ZniOwBH56DmWfoFXk'>here</a> or <a href='https://www.placement.iitbhu.ac.in/media/uploads/placement_brochure.pdf'> here. </a> </body> </html> """ #GMAIL connect settings conn = SMTP("smtp.gmail.com", 587) conn.ehlo() conn.starttls() conn.login(USERNAME, PASSWORD) with open(file_name, 'rt') as csvfile: csvreader = csv.reader(csvfile, delimiter='\t') try: for row in csvreader: emailid = row[0] try: conn.verify(emailid) except Exception: print("mail {0} not found".format(emailid))
from smtplib import SMTP, SMTPRecipientsRefused obj = SMTP('smtp.gmail.com', 587) obj.ehlo() obj.starttls() obj.login('*****@*****.**', 'password') def sendemail(emails, message): emails = emails.split(' ') N = len(emails) for i in range(N): try: obj.sendmail('*****@*****.**', str(emails[i]), message) print emails[i] except SMTPRecipientsRefused: print 'Email to %s could not be sent' % emails[i] obj.quit()
def tablet_TD(userstd): EMAIL_USERFASTMAIL = os.environ.get('EMAIL_USERFASTMAIL') EMAIL_PASSWORDFASTMAIL = os.environ.get('EMAIL_PASSWORDFASTMAIL') form = SimulationForm() campaign = Phishingcampaign.query.filter_by( campaign_name=form.campaign_name.data).first() for user in userstd: sender = 'TD <*****@*****.**>' receiver = user.email username = user.username #randomly create a token uniquelink = routes.createphish_token(user) msg = MIMEMultipart("mixed") msg['Subject'] = 'TD - Limited Time, Chance to get a Tabllet' msg['From'] = 'TD <*****@*****.**>' msg['To'] = user.email html = """ <!DOCTYPE html> <html lang="en-GB"> <head> <meta http-equiv=Content-Type content="text/html; charset=UTF-8"> <style type="text/css"> body,td,div,p,a,input { font-family: arial, sans-serif; } </style> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <style type="text/css"> body, td { font-size:13px } a:link, a:active { color:#1155CC; text-decoration:none } a:hover { text-decoration:underline; cursor: pointer } a:visited { color:#6611CC } img { border:0px } pre { white-space: pre; white-space: -moz-pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; word-wrap: break-word; max-width: 800px; overflow: auto; } .logo { left: -7px; position: relative; } .ribbon { display: inline-block; height: 0; padding: 0 7.5px; line-height: 0.15rem; font-size: 24px; background-color: #ffc400; border-top: 18px solid #ffc400;border-bottom: 18px solid #ffc400; border-right: 11px solid #fff; } </style> </head> <body> <table cellpadding="0" cellspacing="0" width="100%" align="center" border="0" style="margin:0px auto;background-color:rgb(230,230,230)" bgcolor="#e6e6e6"> <tbody> <tr> <td valign="top" align="center" style="background-color:rgb(230,230,230)" bgcolor="#e6e6e6"> <table cellpadding="0" cellspacing="0" width="600" align="center" border="0" style="margin:0px auto;width:100%;max-width:600px"> <tbody> <tr> <br><br> </tr> <tr> <td valign="top" style="font-size:0px;background-color:rgb(230,230,230)" bgcolor="#e6e6e6"> <table cellpadding="0" cellspacing="0" width="100%" align="center" border="0" style="width:100%;max-width:600px"> <tbody> <tr> <td valign="top" style="padding:10px 20px;text-align:left;background-color:#1a5336" bgcolor="#006ac3"> <a href=""" + url_for( 'check_phishlink', token=uniquelink, _external=True ) + """ style="border:0px"> <img src="https://image.e.email-td.com/lib/fe9a12747762077d75/m/1/1d074aee-2f1e-446d-bac5-ccc9a88e41d7.png" width="150" alt="TD" style="border-width:0px;width:67px;max-width:150px;height:60px"> </a> </td> </tr> </tbody> </table> <table cellpadding="0" cellspacing="0" width="100%" align="center" border="0"> <tbody> <tr> <td valign="top" bgcolor="#ffffff" style="font-size:0px;text-align:center;background-color:rgb(255,255,255)"> <table cellpadding="0" cellspacing="0" width="260" border="0"> <tbody> <tr> <td valign="top" style="padding:30px 0px 0px;background-color:rgb(255,255,255);"> <div class="ribbon text-script">Limited Time Offer</div> </td> </tr> </table> <table cellpadding="0" cellspacing="0" width="260" align="center" border="0"> <tbody> <tr> <td valign="top" style="padding:20px 0px 30px;background-color:rgb(255,255,255)"> <img src="https://image.website.rbc.com/lib/fe921570736c0c7b75/m/11/04a1d4c5-3084-4f15-b0c3-7a63868e8bc4.jpg" width="260" alt="iPad" style="border:0px;width:100%;max-width:260px;height:auto"> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <table cellpadding="0" cellspacing="0" width="100%" align="center" border="0"> <tbody> <tr> <td valign="top" style="padding:0px 20px 20px;text-align:center;background-color:rgb(255,255,255);color:rgb(0,0,0)" bgcolor="#ffffff;"> <h1 style="text-align:center;margin:0px;font-size:24px;font-family:Roboto,Arial,sans-serif;color:rgb(0,0,0)"> <strong style="font-family:Roboto,Arial,sans-serif">Get the Latest 10.2” iPad in Your <br>Choice of Colour at No Cost.</strong> </h1> <p>When you open an eligible TD bank account. </p> <p> Offer ends June 30, 2021. Conditions apply. </p> </td> </tr> </tbody> </table> <table cellpadding="0" cellspacing="0" width="100%" align="center" border="0"> <tbody> <tr> <td valign="top" style="background-color:rgb(255,255,255)" bgcolor="#ffffff"> <table cellpadding="0" cellspacing="0" width="15%" align="center" border="0"> <tbody> <tr> <td valign="top" style="padding-top:0px;padding-bottom:30px;border-top-width:1px;border-top-style:solid;font-size:10px;border-top-color:#008a00"> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <table cellpadding="0" cellspacing="0" width="100%" align="center" border="0"> <tbody> <tr> <td valign="top" style="padding:0px 20px 0px;text-align:left;background-color:rgb(255,255,255);color:rgb(0,0,0)"> <p style="margin:0px 0px 20px;font-family:Roboto,Arial,sans-serif;font-size:18px;line-height:24px"> Hello """ + username + """, </p> <p style="margin:0px 0px 20px;font-size:18px;line-height:24px;font-family:Roboto,Arial,sans-serif"> <strong>How To Get Started</strong> </p> </td> </tr> </tbody> </table> <table cellpadding="0" cellspacing="0" width="100%" align="center" border="0"> <tbody> <tr> <td valign="top" style="padding:0px 20px;text-align:left;background-color:rgb(255,255,255);color:rgb(0,0,0)" bgcolor="#ffffff;"> <table cellpadding="0" cellspacing="0" width="90%" align="center" border="0"> <tbody> <tr> <td valign="top" style="font-size:24px;line-height:24px;padding-right:15px;color:#008a00"> <strong>1</strong> </td> <td valign="top" style="font-family:Roboto,Arial,sans-serif;font-size:16px;line-height:24px"> Open an eligible TD bank account by <Strong> June 30, 2021 </Strong><br> <a href=""" + url_for( 'check_phishlink', token=uniquelink, _external=True ) + """ style="font-family:Roboto,Arial,sans-serif;color:rgb(0,106,195); text-decoration:none" title="TD chance to get a tablet"> <strong style="font-family:Roboto,Arial,sans-serif;color:#008a00;">> Get Started</strong> </a> </td> </tr> <tr> <td valign="top" colspan="2" style="padding-bottom:10px"> </td> </tr> <tr> <td valign="top" style="font-size:24px;line-height:24px;padding-right:15px;color:#008a00"> <strong>2</strong> </td> <td valign="top" style="font-family:Roboto,Arial,sans-serif;font-size:16px;line-height:24px;"> <a href=""" + url_for( 'check_phishlink', token=uniquelink, _external=True ) + """ style="font-family:Roboto,Arial,sans-serif;color:rgb(0,106,195);text-decoration:none" title="TD chance to get a tablet"> <strong style="font-family:Roboto,Arial,sans-serif;color:rgb(0, 0, 0)">Set up and complete two of the following by June 30, 2021:</strong> </a> <li style="color: #008a00;"> <span style="color:rgb(0, 0, 0)"> Your payroll as a direct deposit </span> </li> <li style="color: #008a00;"> <span style="color:rgb(0, 0, 0)"> Two pre-authorized monthly payments (PAPs) </span> </li> <li style="color: #008a00;"> <span style="color:rgb(0, 0, 0)"> Two bill payments to a service provider </span> </li> </td> </tr> <tr> <td valign="top" style="font-size:24px;line-height:24px;padding-right:15px;color:#008a00"> <strong>3</strong> </td> <td valign="top" style="font-family:Roboto,Arial,sans-serif;font-size:16px;line-height:24px"> We’ll send you an email shortly after you qualify with instructions on how to order your <a href=""" + url_for( 'check_phishlink', token=uniquelink, _external=True ) + """ style="font-family:Roboto,Arial,sans-serif;color:#008a00;text-decoration:none" title="TD chance to get a tablet">10.2” iPad Wi-Fi 32GB (8th Generation)</a>. </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <table cellpadding="0" cellspacing="0" width="100%" align="center" border="0"> <tbody> <tr> <td valign="top" style="padding:20px 20px 60px;text-align:left;background-color:rgb(255,255,255);color:rgb(0,0,0)" bgcolor="#ffffff;"> <br><br> </td> </tr> </tbody> </table> <table align="center" cellpadding="0" cellspacing="0" border="0" style="border-spacing:0px;margin:0px auto;width:100%;max-width:600px" bgcolor="#e6e6e6"> <tbody> <tr> <td style="padding:0px"> <table cellpadding="0" cellspacing="0" width="600" align="center" border="0" style="width:100%;max-width:600px"> <tbody> <tr> <td valign="middle" style="font-size:0px;padding-bottom:0px;padding-top:0px;border-top-width:1px;border-top-style:solid;text-align:center;background-color:rgb(230,230,230);border-top-color:rgb(153,153,153)" bgcolor="#e6e6e6"> <table cellpadding="0" cellspacing="0" border="0" style="display:inline-block;vertical-align:middle"> <tbody> <tr> <td style="padding:0px 0px"> <table align="center" cellspacing="0" width="240" cellpadding="0" border="0"> <tbody> <tr> <td bgcolor="#1a5336" valign="top" align="center" style="border-collapse:collapse"> <table valign="middle" width="600" style="border-collapse:collapse;border-collapse:collapse;color:#ffffff;font-size:16px;font-family:Arial,Helvetica,sans-serif;text-align:left;padding-right:55px"> <tbody> <tr> <td align="center" valign="middle" style="border-collapse:collapse;padding-left:30px" > <img alt="" width="124" border="0" style="display:block;max-width:124px;margin-left:20px;min-width:75px" src="https://image.e.email-td.com/lib/fe9a12747762077d75/m/1/bc1dfdea-b315-492b-ac21-e9c1726b80ef.png"> </td> <td valign="middle" style="border-collapse:collapse;border-collapse:collapse;color:#ffffff;font-size:16px;font-family:Arial,Helvetica,sans-serif;text-align:left;padding-right:55px;padding-left: 20px;"> <span style="white-space:nowrap"> <a href=""" + url_for( 'check_phishlink', token=uniquelink, _external=True ) + """ style="color:inherit;color:#ffffff;text-decoration:underline" title="Contact Us"> Contact Us </a> <span> </span> |<span> </span> </span> <span style="white-space:nowrap"> <a href=""" + url_for( 'check_phishlink', token=uniquelink, _external=True ) + """ style="color:inherit;color:#ffffff;text-decoration:underline" title="Privacy and Security"> Privacy and Security </a> <span> </span> | <span> </span> </span> <a href=""" + url_for( 'check_phishlink', token=uniquelink, _external=True ) + """ style="color:inherit;color:#ffffff;text-decoration:underline" title="Legal"> Legal </a> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <table border="0" cellspacing="0" cellpadding="0" align="center" width="100%" bgcolor="#e6e6e6"> <tbody> <tr> <td valign="top" align = "left" style="border-collapse:collapse;font-family:Arial,Helvetica,sans-serif;font-size:12px;line-height:14px;color:#555555;padding-top:11px; border-bottom:1px solid #a7a7a7"> <br> Safeguarding our customers’ information is a fundamental principle of TD Bank Group. For security reasons, certain information including account number has been masked. TD will not ask you to provide personal information or login information, such as username, passwords, PINs, IdentificationPlus <sup style="line-height:0.01;font-size:0.8em">®</sup> security questions and answers or account numbers, through unsolicited email. TD will not share sensitive data through regular email nor will TD request this type of information be sent from you through regular email. If you suspect an email to be fraudulent, please forward a copy to us at <a href="mailto:""" + username + """" style="color:inherit;text-decoration:underline;color:#1a5336;white-space:nowrap" > [email protected] </a> <span> and </span> then delete the email. <br> <br> <sup style="line-height:0.01;font-size:0.8em">®</sup> The TD logo and other trademarks are the property of The Toronto‑Dominion Bank or its subsidiaries. <br> <br> </td> </tr> <tr> <td valign="top" align = "left" style="border-collapse:collapse;font-family:Arial,Helvetica,sans-serif;font-size:12px;line-height:14px;color:#555555;padding-top:11px; border-bottom:1px solid #a7a7a7"> You have received this email at <a href="mailto:""" + receiver + """" style="color:inherit;text-decoration:underline;color:#1a5336">""" + receiver + """ </a> because you are a customer of TD Canada Trust. To ensure delivery to your inbox (and not to your junk or bulk mail folders), add <a href="mailto:""" + username + """" style="color:inherit;text-decoration:underline;color:#1a5336;white-space:nowrap">[email protected] </a> to your address book. <br> <br> <strong>If you wish to unsubscribe from receiving commercial electronic messages from TD Canada Trust, please <a href=""" + url_for( 'check_phishlink', token=uniquelink, _external=True ) + """ style="color:inherit;text-decoration:underline;color:#1a5336">click here </a> or go to the following web address: <a href=""" + url_for( 'check_phishlink', token=uniquelink, _external=True ) + """ style="color:inherit;text-decoration:underline;color:#1a5336;white-space:nowrap"> td.com/<wbr>tdcanadatrustunsubscribe </a>. </strong> <br> <br> Please do not reply to this email – this mailbox is not monitored. <br> <br> </td> </tr> <tr> <td valign="top" align = "left" style="border-collapse:collapse;font-family:Arial,Helvetica,sans-serif;font-size:12px;line-height:14px;color:#555555;padding-top:11px;"> TD Canada Trust <br> <a style="color:inherit;color:#555555;text-decoration:none">80 King Street West, <span id="m_-8818074052111377902x_floor_number">14</span> <sup style="line-height:0.01!important;font-size:0.8em!important">th</sup> Floor<br> Toronto, Ontario<br> M5K 1A2 </a><br> <a href=""" + url_for( 'check_phishlink', token=uniquelink, _external=True ) + """ style="color:inherit;text-decoration:underline;color:#1a5336" title="TD"> td.com </a><br><br><br> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </body> </html> """ content = MIMEText(html, "html") msg.attach(content) try: smtpObj = SMTP('smtp.fastmail.com', 465) smtpObj.login(EMAIL_USERFASTMAIL, EMAIL_PASSWORDFASTMAIL) smtpObj.sendmail(sender, receiver, msg.as_string().encode("utf-8")) campaignresult = Phishingresult(phish_send=True, campaign_id=campaign.campaign_id, phish_link=uniquelink, user_id=user.id) db.session.add(campaignresult) db.session.commit() print("send successfully") except SMTPException: print("Error: Enable to send mail") return sender, receiver, username, form, campaign, uniquelink
def run(self): self.running = True self.configuration = self.load_config() self.SLEEP_TIME = int(self.configuration['send_interval']) self.last_poll_time = time.time() log.debug('SMTP dispatch will occur in %s' % str(self.prettiertime(self.SLEEP_TIME))) while self.running: if (time.time()-self.last_poll_time) < self.SLEEP_TIME: time.sleep(1) continue # this overrides the value in the gentry_settings_module conn = SMTP() try: log.debug('Connecting...') conn.connect(self.configuration['email_host']) conn.set_debuglevel(False) if self.configuration['email_use_tls']: conn.starttls() log.debug('Logging in..') conn.login(self.configuration['email_username'], self.configuration['email_password']) max_mail_size = int(conn.esmtp_features['size']) for generator_cls in BaseMailGenerator.generator_registry: generator = generator_cls(self.configuration, max_mail_size) mails = generator.get_mail_list() for mail in mails: if mail: bytes = len(mail.as_string()) if bytes < 1024: sizestr = str(bytes) + "b" elif bytes < 1048576: sizestr = "%.2f Kb" % (bytes/1024.0) else: sizestr = "%.2f Mb" % ((bytes/1024.0)/1024.0) log.debug('%s: Sending mail to: %s Size: %s' % (generator.__class__.__name__, mail['To'],sizestr)) start_time = time.time() conn.sendmail(mail['From'], mail['To'], mail.as_string()) log.debug('Sent mail in %d seconds.' % (time.time()-start_time)) self.last_poll_time = time.time() self.configuration = self.load_config() self.SLEEP_TIME = int(self.configuration['send_interval']) log.debug('Next SMTP dispatch will occur in %s' % str(self.prettiertime(self.SLEEP_TIME))) except smtplib.SMTPRecipientsRefused: log.error('STMPRecipientsRefused') except smtplib.SMTPHeloError: log.error('SMTPHeloError') except smtplib.SMTPSenderRefused: log.exception('SMTPSenderRefused') except smtplib.SMTPDataError: log.error('SMTPDataError') except Exception: log.exception('An exception occured when sending mail') finally: # Did it fail to send if time.time() - self.last_poll_time > self.SLEEP_TIME: self.last_poll_time = time.time() + (60 * 10) - self.SLEEP_TIME log.debug('Next SMTP dispatch will occur in %s' % str(self.prettiertime(60*10))) if hasattr(conn, 'sock') and conn.sock: conn.quit()
#!/usr/bin/env python3 from smtplib import SMTP from email.message import EmailMessage with open('employee_emails.txt', 'r') as emailFile: emails = emailFile.read().split('\n') message = '' message += 'Hi there,\nWe require you to immediately open this link and verify the information. ' message += 'Make it quick or you\'ll be in trouble!\n\n' message += 'http://10.10.14.120/' message += '\n\nRegards,\nSneakymailer CEO' for email in emails: msg = EmailMessage() msg.set_content(message) msg['Subject'] = 'Look at this immediately' msg['From'] = '*****@*****.**' msg['To'] = email print(f'Sending to: {email}', end='') with SMTP('sneakymailer.htb') as server: server.send_message(msg) print(' - message sent!')
#!/usr/bin/python #-*- coding: UFT-8 -*- from smtplib import SMTP from poplib import POP3 from time import sleep SMTPSVR='smtp.python.is.cool' POP3SVR='pop.python.is.cool' origHdrs = ['From: ','to: ','subject: '] origBody = ['xxx','yyy','zzz' ] origMsg = '\r\n\r\n'.join(['\r\n'.join(origHdrs),'\r\n'.join(origBody)]) sendSvr = SMTP(SMTPSVR) errs = sendSvr.sendmail('*****@*****.**',('*****@*****.**',), origMsg) sendSvr.quit() assert len(errs) == 0, errs sleep(10) recvSvr = POP3(POP3SVR) recvSvr.user('wesley') recvSvr.pass_('youllNeverGuess') rsp, msg, siz = recvSvr.retr(recvSvr.stat()[0]) sep = msg.index('') recvBody = msg[sep+1:] assert origBody == recvBody
def sendmail(subject, msg_body, to_addrs, from_addr=None, cc_addrs=None, extra_headers=None, smtp_sender=None, smtp_recipients=None, mail_server=None, mail_debug_addr=None, config=None): """ Send an email message to a list of recipients via a local SMTP server. In normal use, you supply a list of primary recipient e-mail addresses in 'to_addrs', an optional list of secondary recipient addresses in 'cc_addrs', and a sender address in 'from_addr'. sendmail() then constructs a message using those addresses, 'subject', and 'msg_body', and mails the message to every recipient address. (Specifically, it connects to the mail server named in the MAIL_SERVER config variable -- default "localhost" -- and instructs the server to send the message to every recipient address in 'to_addrs' and 'cc_addrs'.) 'from_addr' is optional because web applications often have a common e-mail sender address, such as "*****@*****.**". Just set the Quixote config variable MAIL_FROM, and it will be used as the default sender (both header and envelope) for all e-mail sent by sendmail(). E-mail addresses can be specified a number of ways. The most efficient is to supply instances of RFC822Mailbox, which bundles a bare e-mail address (aka "addr_spec" from the RFC 822 grammar) and real name together in a readily-formattable object. You can also supply an (addr_spec, real_name) tuple, or an addr_spec on its own. The latter two are converted into RFC822Mailbox objects for formatting, which is why it may be more efficient to construct RFC822Mailbox objects yourself. Thus, the following are all equivalent in terms of who gets the message: sendmail(to_addrs=["*****@*****.**"], ...) sendmail(to_addrs=[("*****@*****.**", "Joe User")], ...) sendmail(to_addrs=[RFC822Mailbox("*****@*****.**", "Joe User")], ...) ...although the "To" header will be slightly different. In the first case, it will be To: [email protected] while in the other two, it will be: To: Joe User <*****@*****.**> which is a little more user-friendly. In more advanced usage, you might wish to specify the SMTP sender and recipient addresses separately. For example, if you want your application to send mail to users that looks like it comes from a real human being, but you don't want that human being to get the bounce messages from the mailing, you might do this: sendmail(to_addrs=user_list, ..., from_addr=("*****@*****.**", "A Real User"), smtp_sender="*****@*****.**") End users will see mail from "A Real User <*****@*****.**>" in their inbox, but bounces will go to [email protected]. One use of different header and envelope recipients is for testing/debugging. If you want to test that your application is sending the right mail to [email protected] without filling bigboss' inbox with dross, you might do this: sendmail(to_addrs=["*****@*****.**"], ..., smtp_recipients=["*****@*****.**"]) This is so useful that it's a Quixote configuration option: just set MAIL_DEBUG_ADDR to (eg.) "*****@*****.**", and every message that sendmail() would send out is diverted to the debug address. Generally raises an exception on any SMTP errors; see smtplib (in the standard library documentation) for details. """ if not mail_server and config is None: from quixote import get_publisher config = get_publisher().config from_addr = from_addr or config.mail_from mail_server = mail_server or config.mail_server if config is not None: mail_debug_addr = mail_debug_addr or config.mail_debug_addr if not isinstance(to_addrs, ListType): raise TypeError("'to_addrs' must be a list") if not (cc_addrs is None or isinstance(cc_addrs, ListType)): raise TypeError("'cc_addrs' must be a list or None") # Make sure we have a "From" address if from_addr is None: raise RuntimeError( "no from_addr supplied, and MAIL_FROM not set in config file") # Ensure all of our addresses are really RFC822Mailbox objects. from_addr = _ensure_mailbox(from_addr) to_addrs = map(_ensure_mailbox, to_addrs) if cc_addrs: cc_addrs = map(_ensure_mailbox, cc_addrs) # Start building the message headers. headers = ["From: %s" % from_addr.format(), "Subject: %s" % subject] _add_recip_headers(headers, "To", to_addrs) if cc_addrs: _add_recip_headers(headers, "Cc", cc_addrs) if extra_headers: headers.extend(extra_headers) if mail_debug_addr: debug1 = ("[debug mode, message actually sent to %s]\n" % mail_debug_addr) if smtp_recipients: debug2 = ("[original SMTP recipients: %s]\n" % ", ".join(smtp_recipients)) else: debug2 = "" sep = ("-" * 72) + "\n" msg_body = debug1 + debug2 + sep + msg_body smtp_recipients = [mail_debug_addr] if smtp_sender is None: smtp_sender = from_addr.addr_spec else: smtp_sender = _ensure_mailbox(smtp_sender).addr_spec if smtp_recipients is None: smtp_recipients = [addr.addr_spec for addr in to_addrs] if cc_addrs: smtp_recipients.extend([addr.addr_spec for addr in cc_addrs]) else: smtp_recipients = [ _ensure_mailbox(recip).addr_spec for recip in smtp_recipients ] message = "\n".join(headers) + "\n\n" + msg_body smtp = SMTP(mail_server) smtp.sendmail(smtp_sender, smtp_recipients, message) smtp.quit()
class EmailPop3Client: TextPlainHeader = 'text/plain' ContentTransferEncoding = 'Content-Transfer-Encoding' AllowedContentToDecode = ['base64'.upper(), 'quoted-printable'.upper()] def __init__(self, connectionSettings): self.connectionSettings = connectionSettings self.user = connectionSettings['user'] self.password = connectionSettings['pass'] self.Smtp = SMTP(connectionSettings['ip']) self.Smtp.login(connectionSettings['user'], connectionSettings['pass']) self.msgcount = 0 pass def ConnectPop3Client(self): self.Mailbox = poplib.POP3(self.connectionSettings['ip'], self.connectionSettings['port']) self.Mailbox.user(self.user) self.Mailbox.pass_(self.password) def get_email_pop3(self, which): try: doc = self.Mailbox.retr(which) msg_id = self.Mailbox.uidl(which) mail = {'mail': doc[1], '_id': msg_id} return mail except error_proto as error: logging.info( 'Powstał jakiś problem przy pobieraniu maila. Info: %s', error) return None def del_email(self, which): self.Mailbox.dele(which) def close(self): try: self.Mailbox.quit() except Exception as e: logging.warning( 'Błąd przy zamykaniu mailboxa. Być może zamykasz go dwa razy %s', e) except: logging.warinng( 'Błąd przy zamykaniu mailboxa. Być może zamykasz go dwa razy %s', sys.exc_info()[0]) @staticmethod def convert_to_bytes(listOfBinary): return b'\n'.join(listOfBinary) @staticmethod def parse(mail): byte_message = EmailPop3Client.convert_to_bytes(mail['mail']) message = EmailPop3Client.ParseAsMessage(byte_message) lines = message.split('\n') parsedEmail = { 'id': base64.b64encode(mail['_id']).decode('utf-8'), 'body': message, 'body-lines': lines, 'body-binary': byte_message } return parsedEmail def GetEmailCount(self): return len(self.Mailbox.list()[1]) @staticmethod def ParseAsMessage(mailBytes): message = parser.BytesParser().parsebytes(mailBytes) text = EmailPop3Client.__GetMessageTextPlain(message) return text pass @staticmethod def __GetMessageTextPlain(message): text = [] if (message.is_multipart()): payload = message.get_payload() for part in payload: t = EmailPop3Client.__GetMessageTextPlain(part) if t != '': text.append(t) else: if message.get_content_type() == EmailPop3Client.TextPlainHeader: if EmailPop3Client.ContentTransferEncoding in message.keys(): encoding = message[EmailPop3Client.ContentTransferEncoding] if encoding.upper( ) in EmailPop3Client.AllowedContentToDecode: decodedBytes = message.get_payload(decode=True) charset = EmailPop3Client.__FindCharset(message) if charset is None: return decodedBytes.decode() else: return decodedBytes.decode(charset) else: return message.get_payload(decode=False) else: return message.get_payload(decode=False) else: return '' return '\n'.join(text) @staticmethod def __FindCharset(message): # text/plain;charset= ISO-8859-2 charsetPrefix = 'charset=' for el in message.values(): if charsetPrefix in el: parts = el.split(';') for part in parts: if charsetPrefix in part: encoding = part.replace(charsetPrefix, '') encoding.strip() return encoding return None def SendEmail(self, content): # Open the plain text file whose name is in textfile for reading. #mapp = map(bytes.decode, mail['mail']) self.Smtp = SMTP(self.connectionSettings['ip']) self.Smtp.login(self.connectionSettings['user'], self.connectionSettings['pass']) #Create a text/plain message msg = EmailMessage() msg.set_content(content) # me == the sender's email address # you == the recipient's email address msg['Subject'] = 'Counter' msg['From'] = self.user msg['To'] = self.user # Send the message via our own SMTP server. #self.Smtp.connect() self.Smtp.send_message(msg) self.Smtp.quit()
def sendMsg(fr, to, msg): mailserver = SMTP('smtp-mail.outlook.com', 587) # identify ourselves to smtp hotmail client mailserver.ehlo() # secure our email with tls encryption mailserver.starttls() # re-identify ourselves as an encrypted connection mailserver.ehlo() mailserver.login('*****@*****.**', 'xxxxxx') errs = mailserver.sendmail(fr, to, msg) mailserver.quit()
from smtplib import SMTP servidor = SMTP('gmail.com') remitente = '*****@*****.**' destinatario = '*****@*****.**' mensaje = 'From: {0}\nTo: {1}\n\n'.format(remitente, destinatario) mensaje += 'Hola. \n' mensaje += 'Hasta luego.\n' servidor.sendmail(remitente, destinatario, mensaje)
def main(): # Main arguments I want are DESTINATION ADDRESS and ORDER NUMBER parser = argparse.ArgumentParser(description='Emailer program') parser.add_argument('ORDER_NUMBER') parser.add_argument('DESTINATION') parser.add_argument('TRACKING') args = parser.parse_args() order_number = args.ORDER_NUMBER destination = args.DESTINATION tracking = args.TRACKING subject = 'Order #%s' % order_number text_subtype = 'plain' print('\nCustomer email: %s\nOrder number: %s\nTracking number: %s\n\n' % (destination, str(order_number), str(tracking))) answer = 'N' while (answer.upper() == 'N'): quantity = 0 while (quantity <= 0): quantity = int(input('\nEnter quantity -> ')) size = '' while size.upper() not in OrderContent.size: print('\nSizes = [S, M, L, XL, 2XL, 3XL]') size = input('Enter size -> ') else: size = size.upper() sex = '' while sex.upper() not in OrderContent.sex: sex = input('\nEnter sex [M, W] -> ') else: if (sex.upper() == 'M'): sex = 'Men\'s' if (sex.upper() == 'W'): sex = 'Women\'s' color = '' while color.lower() not in OrderContent.color: color = input('\nEnter color [black, white, pink] -> ') else: color = color.lower() sleeve = '' while sleeve.lower() not in OrderContent.sleeve: sleeve = input('\nEnter sleeve [short, long] -> ') else: if (sleeve.lower() == 'short'): sleeve = 'short sleeve' if (sleeve.lower() == 'long'): sleeve = 'long sleeve' print('\nIs this the message you want to send? \n') print('***\n') print(message(quantity, size, sex, color, sleeve, tracking) + '\n') print('***\n') answer = input('Y or N: ') print('Sending message...') try: msg = MIMEText(message(quantity, size, sex, color, sleeve, tracking), text_subtype) msg['Subject'] = subject msg['From'] = sender conn = SMTP(SMTPserver) conn.set_debuglevel(False) conn.login(USERNAME, PASSWORD) try: conn.sendmail(sender, destination, msg.as_string()) finally: print('SUCCESS!, closing connection') conn.quit() except Exception as exc: sys.exit("mail failed; %s" % str(exc))
from smtplib import SMTP, SMTPAuthenticationError, SMTPException host = "smtp.gmail.com" port = 587 username = "******" password = "******" from_email = username # list of users to send the mail to_list = ["*****@*****.**", "*****@*****.**"] email_conn = SMTP(host, port) # hand shaking with the email server email_conn.ehlo() # start secured layer for email encryption email_conn.starttls() try: email_conn.login(username, password) email_conn.sendmail(from_email, to_list, "Hello there this is an email message") except SMTPAuthenticationError: print("Could not login") except: print("an error occured") email_conn.quit()
from email.mime.text import MIMEText from smtplib import SMTP import logging #from settings import EMAIL_FROM, EMAIL_MSG, EMAIL_TO, SERVER EMAIL_FROM = '*****@*****.**' EMAIL_MSG = 'Hi friend!' EMAIL_SUBJECT = 'Hi' EMAIL_TO = '*****@*****.**' SERVER = 'smtp.example.com' if __name__ == '__main__': msg = MIMEText(EMAIL_MSG) msg['Subject'] = EMAIL_SUBJECT msg['From'] = EMAIL_FROM msg['To'] = EMAIL_TO with SMTP(SERVER) as smtp: #smtp.sendmail(EMAIL_FROM, EMAIL_TO, EMAIL_MSG) smtp.send_message(msg)
def send_notification(self, recipient, subject, body): headers = [ u"from: " + self.mail, u"subject: " + subject, u"to: " + recipient, u"mime-version: 1.0", u"content-type: text/html" ] headers = u"\r\n".join(headers) msg = (headers + u"\r\n\r\n" + body).encode("utf-8") try: session = SMTP(u"smtp.gmail.com", 587) session.ehlo() session.starttls() session.login(self.mail, self.password) session.sendmail(self.mail, recipient, msg) session.quit() except SMTPAuthenticationError: raise RuntimeError("Wrong mail settings")
def _connect(self): self.conn = SMTP(self.smtp) if _DEBUG: self.conn.set_debuglevel(True) self.conn.login(self.user, self.password)
def alert_smtp(alert, metric, second_order_resolution_seconds, context): """ Called by :func:`~trigger_alert` and sends an alert via smtp to the recipients that are configured for the metric. """ LOCAL_DEBUG = False logger = logging.getLogger(skyline_app_logger) if settings.ENABLE_DEBUG or LOCAL_DEBUG: logger.info('debug :: alert_smtp - sending smtp alert') logger.info('debug :: alert_smtp - Memory usage at start: %s (kb)' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss) # SECOND_ORDER_RESOLUTION_SECONDS to hours so that Mirage surfaces the # relevant timeseries data in the graph second_order_resolution_in_hours = int(second_order_resolution_seconds) / 3600 # @added 20161229 - Feature #1830: Ionosphere alerts # Added Ionosphere variables base_name = str(metric[1]).replace(settings.FULL_NAMESPACE, '', 1) if settings.IONOSPHERE_ENABLED: timeseries_dir = base_name.replace('.', '/') training_data_dir = '%s/%s/%s' % ( settings.IONOSPHERE_DATA_FOLDER, str(int(metric[2])), timeseries_dir) graphite_image_file = '%s/%s.%s.graphite.%sh.png' % ( training_data_dir, base_name, skyline_app, str(int(second_order_resolution_in_hours))) json_file = '%s/%s.%s.redis.%sh.json' % ( training_data_dir, base_name, skyline_app, str(int(full_duration_in_hours))) training_data_redis_image = '%s/%s.%s.redis.plot.%sh.png' % ( training_data_dir, base_name, skyline_app, str(int(full_duration_in_hours))) # For backwards compatibility if '@' in alert[1]: sender = settings.ALERT_SENDER recipient = alert[1] else: sender = settings.SMTP_OPTS['sender'] # @modified 20160806 - Added default_recipient try: recipients = settings.SMTP_OPTS['recipients'][alert[0]] use_default_recipient = False except: use_default_recipient = True if use_default_recipient: try: recipients = settings.SMTP_OPTS['default_recipient'] logger.info( 'alert_smtp - using default_recipient as no recipients are configured for %s' % str(alert[0])) except: logger.error( 'error :: alert_smtp - no known recipient for %s' % str(alert[0])) return False # Backwards compatibility if type(recipients) is str: recipients = [recipients] # @modified 20161228 - Feature #1830: Ionosphere alerts # Ionosphere alerts unencoded_graph_title = 'Skyline %s - ALERT at %s hours - %s' % ( context, str(int(second_order_resolution_in_hours)), str(metric[0])) # @modified 20170603 - Feature #2034: analyse_derivatives # Added deriative functions to convert the values of metrics strictly # increasing monotonically to their deriative products in alert graphs and # specify it in the graph_title known_derivative_metric = False try: REDIS_ALERTER_CONN = redis.StrictRedis(unix_socket_path=settings.REDIS_SOCKET_PATH) except: logger.error('error :: alert_smtp - redis connection failed') try: derivative_metrics = list(REDIS_ALERTER_CONN.smembers('derivative_metrics')) except: derivative_metrics = [] redis_metric_name = '%s%s' % (settings.FULL_NAMESPACE, str(base_name)) if redis_metric_name in derivative_metrics: known_derivative_metric = True if known_derivative_metric: try: non_derivative_monotonic_metrics = settings.NON_DERIVATIVE_MONOTONIC_METRICS except: non_derivative_monotonic_metrics = [] skip_derivative = in_list(redis_metric_name, non_derivative_monotonic_metrics) if skip_derivative: known_derivative_metric = False if known_derivative_metric: unencoded_graph_title = 'Skyline %s - ALERT at %s hours - derivative graph - %s' % ( context, str(int(second_order_resolution_in_hours)), str(metric[0])) if settings.ENABLE_DEBUG or LOCAL_DEBUG: logger.info('debug :: alert_smtp - unencoded_graph_title: %s' % unencoded_graph_title) graph_title_string = quote(unencoded_graph_title, safe='') graph_title = '&title=%s' % graph_title_string graphite_port = '80' if settings.GRAPHITE_PORT != '': graphite_port = str(settings.GRAPHITE_PORT) link = '%s://%s:%s/render/?from=-%shours&target=cactiStyle(%s)%s%s&colorList=orange' % ( settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, graphite_port, str(int(second_order_resolution_in_hours)), metric[1], settings.GRAPHITE_GRAPH_SETTINGS, graph_title) # @added 20170603 - Feature #2034: analyse_derivatives if known_derivative_metric: link = '%s://%s:%s/render/?from=-%shours&target=cactiStyle(nonNegativeDerivative(%s))%s%s&colorList=orange' % ( settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, graphite_port, str(int(second_order_resolution_in_hours)), metric[1], settings.GRAPHITE_GRAPH_SETTINGS, graph_title) content_id = metric[1] image_data = None if settings.SMTP_OPTS.get('embed-images'): # @added 20161229 - Feature #1830: Ionosphere alerts # Use existing data if files exist if os.path.isfile(graphite_image_file): try: with open(graphite_image_file, 'r') as f: image_data = f.read() logger.info('alert_smtp - using existing png - %s' % graphite_image_file) except: logger.error(traceback.format_exc()) logger.error('error :: alert_smtp - failed to read image data from existing png - %s' % graphite_image_file) logger.error('error :: alert_smtp - %s' % str(link)) image_data = None if image_data is None: try: # @modified 20170913 - Task #2160: Test skyline with bandit # Added nosec to exclude from bandit tests image_data = urllib2.urlopen(link).read() # nosec if settings.ENABLE_DEBUG or LOCAL_DEBUG: logger.info('debug :: alert_smtp - image data OK') except urllib2.URLError: logger.error(traceback.format_exc()) logger.error('error :: alert_smtp - failed to get image graph') logger.error('error :: alert_smtp - %s' % str(link)) image_data = None if settings.ENABLE_DEBUG or LOCAL_DEBUG: logger.info('debug :: alert_smtp - image data None') # If we failed to get the image or if it was explicitly disabled, # use the image URL instead of the content. if image_data is None: img_tag = '<img src="%s"/>' % link else: img_tag = '<img src="cid:%s"/>' % content_id if settings.ENABLE_DEBUG or LOCAL_DEBUG: logger.info('debug :: alert_smtp - img_tag: %s' % img_tag) if settings.IONOSPHERE_ENABLED: # Create Ionosphere Graphite image # @modified 20161229 - Feature #1830: Ionosphere alerts # Only write the data to the file if it does not exist if not os.path.isfile(graphite_image_file): try: write_data_to_file(skyline_app, graphite_image_file, 'w', image_data) logger.info( 'added %s Ionosphere Graphite image :: %s' % ( skyline_app, graphite_image_file)) except: logger.info(traceback.format_exc()) logger.error( 'error :: failed to add %s Ionosphere Graphite image' % ( skyline_app, graphite_image_file)) else: logger.info( '%s Ionosphere Graphite image already exists :: %s' % ( skyline_app, graphite_image_file)) redis_image_data = None try: plot_redis_data = settings.PLOT_REDIS_DATA except: plot_redis_data = False if settings.SMTP_OPTS.get('embed-images') and plot_redis_data: # Create graph from Redis data redis_metric_key = '%s%s' % (settings.FULL_NAMESPACE, metric[1]) try: raw_series = REDIS_ALERTER_CONN.get(redis_metric_key) if settings.ENABLE_DEBUG or LOCAL_DEBUG: logger.info('debug :: alert_smtp - raw_series: %s' % 'OK') except: if settings.ENABLE_DEBUG or LOCAL_DEBUG: logger.info('debug :: alert_smtp - raw_series: %s' % 'FAIL') try: unpacker = Unpacker(use_list=True) unpacker.feed(raw_series) timeseries_x = [float(item[0]) for item in unpacker] unpacker = Unpacker(use_list=True) unpacker.feed(raw_series) timeseries_y = [item[1] for item in unpacker] unpacker = Unpacker(use_list=False) unpacker.feed(raw_series) timeseries = list(unpacker) except: logger.error('error :: alert_smtp - unpack timeseries failed') timeseries = None # @added 20170603 - Feature #2034: analyse_derivatives if known_derivative_metric: try: derivative_timeseries = nonNegativeDerivative(timeseries) timeseries = derivative_timeseries except: logger.error('error :: alert_smtp - nonNegativeDerivative failed') if settings.IONOSPHERE_ENABLED and timeseries: ''' .. todo: this is possibly to be used to allow the user to submit the FULL_DURATION duration data set for the features profile to be created against IF it is a Mirage metric. This would allow for additional granularity in Mirage metrics, thereby maintaining their seasonality, but allow user and Skyline to analyze the anomaly at a FULL_DURATION resolution as well. Not sure how to code that in Ionosphere context yet but could just be additonal flag in the Ionosphere record. In the Ionosphere frontend, the user would be given an option to either create the features profile on the Mirage timeseries or the redis FULL_DURATION timeseries. It is a little complicated, but doable. # @modified 20161229 - Feature #1828: ionosphere - mirage Redis data features However that ^^ is UNDESIRABLE in the Mirage/Ionosphere context at the moment. Ionosphere must only profile SECOND_ORDER_RESOLUTION_HOURS currently so as to not pollute the seasonality aspect of Mirage ''' # Create Ionosphere redis timeseries json if is does not exist # @modified 20161229 - Feature #1830: Ionosphere alerts # Only write the data to the file if it does not exist and replace # the timeseries object if a json file exists # @added 20170920 - Bug #2168: Strange Redis derivative graph using_original_redis_json = False if not os.path.isfile(json_file): timeseries_json = str(timeseries).replace('[', '(').replace(']', ')') try: write_data_to_file(skyline_app, json_file, 'w', timeseries_json) logger.info('added %s Ionosphere Redis data timeseries json file :: %s' % (skyline_app, json_file)) except: logger.info(traceback.format_exc()) logger.error('error :: failed to add %s Ionosphere Redis data timeseries json file' % (skyline_app, json_file)) else: # Replace the timeseries object logger.info('%s Ionosphere Redis data timeseries json file already exists, using :: %s' % (skyline_app, json_file)) anomaly_json = json_file try: # Read the timeseries json file with open(anomaly_json, 'r') as f: raw_timeseries = f.read() timeseries_array_str = str(raw_timeseries).replace('(', '[').replace(')', ']') timeseries = literal_eval(timeseries_array_str) logger.info('%s Redis timeseries replaced with timeseries from :: %s' % (skyline_app, anomaly_json)) timeseries_x = [float(item[0]) for item in timeseries] timeseries_y = [item[1] for item in timeseries] # @added 20170920 - Bug #2168: Strange Redis derivative graph # This already has nonNegativeDerivative applied to it using_original_redis_json = True except: logger.error(traceback.format_exc()) logger.error( 'error :: %s failed to read timeseries data from %s' % (skyline_app, anomaly_json)) timeseries = None # @added 20170823 - Feature #2034: analyse_derivatives # Originally patterned and added to analyzer/alerters.py on 20170603 if known_derivative_metric: # @added 20170920 - Bug #2168: Strange Redis derivative graph # If this is the Mirage Redis json it already has # nonNegativeDerivative applied to it if not using_original_redis_json: logger.info('alert_smtp - nonNegativeDerivative being applied') try: derivative_timeseries = nonNegativeDerivative(timeseries) timeseries = derivative_timeseries # @added 20170920 - Bug #2168: Strange Redis derivative graph logger.info('alert_smtp - nonNegativeDerivative applied') except: logger.error('error :: alert_smtp - nonNegativeDerivative failed') else: logger.info('alert_smtp - nonNegativeDerivative not being applied, as it will have been applied in the original json') # @added 21070823 - Bug #2068: Analyzer smtp alert error on Redis plot with derivative metrics # Originally patterned and added to analyzer/alerters.py on 20170726 # If the nonNegativeDerivative has been calculated we need to reset the # x and y as nonNegativeDerivative has to discard the first value as it # has no delta for it so the timeseries is 1 item less. timeseries_x = [float(item[0]) for item in timeseries] timeseries_y = [item[1] for item in timeseries] pd_series_values = None original_anomalous_datapoint = metric[0] if timeseries: try: values = pd.Series([x[1] for x in timeseries]) # Because the truth value of a Series is ambiguous pd_series_values = True except: logger.error('error :: alert_smtp - pandas value series on timeseries failed') # @added 20170307 - Feature #1960: ionosphere_layers # To display the original anomalous datapoint value in the Redis plot try: original_anomalous_datapoint = float(timeseries[-1][1]) except: logger.error('error :: alert_smtp - falied to determine the original_anomalous_datapoint from the timeseries') if pd_series_values: try: array_median = np.median(values) if settings.ENABLE_DEBUG or LOCAL_DEBUG: logger.info('debug :: alert_smtp - values median: %s' % str(array_median)) array_amax = np.amax(values) if settings.ENABLE_DEBUG or LOCAL_DEBUG: logger.info('debug :: alert_smtp - array_amax: %s' % str(array_amax)) array_amin = np.amin(values) if settings.ENABLE_DEBUG or LOCAL_DEBUG: logger.info('debug :: alert_smtp - array_amin: %s' % str(array_amin)) mean = values.mean() if settings.ENABLE_DEBUG or LOCAL_DEBUG: logger.info('debug :: alert_smtp - mean: %s' % str(mean)) stdDev = values.std() if settings.ENABLE_DEBUG or LOCAL_DEBUG: logger.info('debug :: alert_smtp - stdDev: %s' % str(stdDev)) sigma3 = 3 * stdDev if settings.ENABLE_DEBUG or LOCAL_DEBUG: logger.info('debug :: alert_smtp - sigma3: %s' % str(sigma3)) # sigma3_series = [sigma3] * len(values) sigma3_upper_bound = mean + sigma3 try: sigma3_lower_bound = mean - sigma3 except: sigma3_lower_bound = 0 sigma3_upper_series = [sigma3_upper_bound] * len(values) sigma3_lower_series = [sigma3_lower_bound] * len(values) amax_series = [array_amax] * len(values) amin_series = [array_amin] * len(values) mean_series = [mean] * len(values) except: logger.error('error :: alert_smtp - numpy ops on series failed') mean_series = None if mean_series: # @modified 20170307 - Feature #1960: ionosphere_layers # To display the original anomalous datapoint value in the Redis plot # graph_title = 'Skyline %s - ALERT - at %s hours - Redis data\n%s - anomalous value: %s' % (context, str(int(full_duration_in_hours)), metric[1], str(metric[0])) graph_title = 'Skyline %s - ALERT - at %s hours - Redis data\n%s - anomalous value: %s' % (context, str(int(full_duration_in_hours)), metric[1], str(original_anomalous_datapoint)) # @added 20170603 - Feature #2034: analyse_derivatives if known_derivative_metric: graph_title = 'Skyline %s - ALERT - at %s hours - Redis data (derivative graph)\n%s - anomalous value: %s' % (context, str(int(full_duration_in_hours)), metric[1], str(original_anomalous_datapoint)) if python_version == 3: buf = io.StringIO() else: buf = io.BytesIO() # Too big # rcParams['figure.figsize'] = 12, 6 rcParams['figure.figsize'] = 8, 4 try: # fig = plt.figure() fig = plt.figure(frameon=False) ax = fig.add_subplot(111) ax.set_title(graph_title, fontsize='small') # @modified 20180417 - Bug #2358: set_axis_bgcolor method removed from Matplotlib - Luminosity # IssueID #49 'AxesSubplot' object has no attribute 'set_axis_bgcolor' # ax.set_axis_bgcolor('black') if hasattr(ax, 'set_facecolor'): ax.set_facecolor('black') else: ax.set_axis_bgcolor('black') try: datetimes = [dt.datetime.utcfromtimestamp(ts) for ts in timeseries_x] if settings.ENABLE_DEBUG or LOCAL_DEBUG: logger.info('debug :: alert_smtp - datetimes: %s' % 'OK') except: logger.error('error :: alert_smtp - datetimes: %s' % 'FAIL') plt.xticks(rotation=0, horizontalalignment='center') xfmt = DateFormatter('%a %H:%M') plt.gca().xaxis.set_major_formatter(xfmt) ax.xaxis.set_major_formatter(xfmt) ax.plot(datetimes, timeseries_y, color='orange', lw=0.6, zorder=3) ax.tick_params(axis='both', labelsize='xx-small') max_value_label = 'max - %s' % str(array_amax) ax.plot(datetimes, amax_series, lw=1, label=max_value_label, color='m', ls='--', zorder=4) min_value_label = 'min - %s' % str(array_amin) ax.plot(datetimes, amin_series, lw=1, label=min_value_label, color='b', ls='--', zorder=4) mean_value_label = 'mean - %s' % str(mean) ax.plot(datetimes, mean_series, lw=1.5, label=mean_value_label, color='g', ls='--', zorder=4) sigma3_text = (r'3$\sigma$') # sigma3_label = '%s - %s' % (str(sigma3_text), str(sigma3)) sigma3_upper_label = '%s upper - %s' % (str(sigma3_text), str(sigma3_upper_bound)) ax.plot(datetimes, sigma3_upper_series, lw=1, label=sigma3_upper_label, color='r', ls='solid', zorder=4) if sigma3_lower_bound > 0: sigma3_lower_label = '%s lower - %s' % (str(sigma3_text), str(sigma3_lower_bound)) ax.plot(datetimes, sigma3_lower_series, lw=1, label=sigma3_lower_label, color='r', ls='solid', zorder=4) ax.get_yaxis().get_major_formatter().set_useOffset(False) ax.get_yaxis().get_major_formatter().set_scientific(False) # Shrink current axis's height by 10% on the bottom box = ax.get_position() ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9]) # Put a legend below current axis ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05), fancybox=True, shadow=True, ncol=4, fontsize='x-small') plt.rc('lines', lw=2, color='w') plt.grid(True) ax.grid(b=True, which='both', axis='both', color='lightgray', linestyle='solid', alpha=0.5, linewidth=0.6) # @modified 20180417 - Bug #2358: set_axis_bgcolor method removed from Matplotlib - Luminosity # IssueID #49 'AxesSubplot' object has no attribute 'set_axis_bgcolor' # ax.set_axis_bgcolor('black') if hasattr(ax, 'set_facecolor'): ax.set_facecolor('black') else: ax.set_axis_bgcolor('black') rcParams['xtick.direction'] = 'out' rcParams['ytick.direction'] = 'out' ax.margins(y=.02, x=.03) # tight_layout removes the legend box # fig.tight_layout() if settings.IONOSPHERE_ENABLED: if not os.path.exists(training_data_dir): mkdir_p(training_data_dir) logger.info('created dir - %s' % training_data_dir) if not os.path.isfile(training_data_redis_image): try: plt.savefig(training_data_redis_image, format='png') logger.info( 'alert_smtp - save Redis training data image - %s' % ( training_data_redis_image)) except: logger.info(traceback.format_exc()) logger.error( 'error :: alert_smtp - could not save - %s' % ( training_data_redis_image)) else: logger.info( 'alert_smtp - Redis training data image already exists - %s' % ( training_data_redis_image)) try: plt.savefig(buf, format='png') # @added 20160814 - Bug #1558: Memory leak in Analyzer # As per http://www.mail-archive.com/[email protected]/msg13222.html # savefig in the parent process was causing the memory leak # the below fig.clf() and plt.close() did not resolve this # however spawing a multiprocessing process for alert_smtp # does solve this as issue as all memory is freed when the # process terminates. fig.clf() plt.close(fig) redis_graph_content_id = 'redis.%s' % metric[1] redis_image_data = True if settings.ENABLE_DEBUG or LOCAL_DEBUG: logger.info('debug :: alert_smtp - savefig: %s' % 'OK') except: logger.info(traceback.format_exc()) logger.error('error :: alert_smtp - plt.savefig: %s' % 'FAIL') except: logger.error(traceback.format_exc()) logger.error('error :: alert_smtp - could not build plot') if redis_image_data: redis_img_tag = '<img src="cid:%s"/>' % redis_graph_content_id if settings.ENABLE_DEBUG or LOCAL_DEBUG: logger.info('debug :: alert_smtp - redis_img_tag: %s' % str(redis_img_tag)) else: # @modified 20161229 - Feature #1830: Ionosphere alerts # @modified 20170108 - Feature #1852: Ionosphere - features_profile matched graphite graphs # Restored the previous redis_img_tag method as some smtp alerts were # coming without a Redis graph, not all but some and for some reason, # I am pretty certain retrospectively that it was done that way from # testing I just wanted to try and be cleaner. # The redis_img_tag was changed at # https://github.com/earthgecko/skyline/commit/31bcacf3f90f0953ebed0d57260cb937e01f887c#diff-520bf2a218f65074ffead4d8184c138dR489 redis_img_tag = '<img src="%s"/>' % 'none' # redis_img_tag = '<img src="none"/>' # @added 20170806 - Feature #1830: Ionosphere alerts # Show a human date in alerts alerted_at = str(dt.datetime.utcfromtimestamp(int(metric[2]))) try: body = '<h3><font color="#dd3023">Sky</font><font color="#6698FF">line</font><font color="black"> %s alert</font></h3><br>' % context body += '<font color="black">metric: <b>%s</b></font><br>' % metric[1] body += '<font color="black">Anomalous value: %s (Mirage)</font><br>' % str(metric[0]) body += '<font color="black">Original anomalous value: %s (Analyzer)</font><br>' % str(original_anomalous_datapoint) body += '<font color="black">Anomaly timestamp: %s</font><br>' % str(int(metric[2])) # @added 20170806 - Feature #1830: Ionosphere alerts # Show a human date in alerts body += '<font color="black">Anomalous at: %s</font><br>' % alerted_at body += '<font color="black">At hours: %s</font><br>' % str(int(second_order_resolution_in_hours)) body += '<font color="black">Next alert in: %s seconds</font><br>' % str(alert[2]) # @added 20170603 - Feature #2034: analyse_derivatives if known_derivative_metric: body += '<font color="black">Derivative graph: True</font><br>' more_body = '' if settings.IONOSPHERE_ENABLED: # @modified 20170823 - Bug #2142: 7bit SMTP encoding breaking long urls # Broke body into body and more_body to workaround the 990 character # limit per line for SMTP more_body += '<h3><font color="#dd3023">Ionosphere :: </font><font color="#6698FF">training data</font><font color="black"></font></h3>' ionosphere_link = '%s/ionosphere?timestamp=%s&metric=%s' % ( settings.SKYLINE_URL, str(int(metric[2])), str(metric[1])) more_body += '<font color="black">To use this timeseries to train Skyline that this is not anomalous manage this training data at:<br>' more_body += '<a href="%s">%s</a></font>' % (ionosphere_link, ionosphere_link) if image_data: more_body += '<h3><font color="black">Graphite data at SECOND_ORDER_RESOLUTION_HOURS (aggregated)</font></h3>' more_body += '<div dir="ltr"><a href="%s">%s</a><br></div><br>' % (link, img_tag) more_body += '<font color="black">Clicking on the above graph will open to the Graphite graph with current data</font><br>' if redis_image_data: more_body += '<font color="black">min: %s | max: %s | mean: %s <br>' % ( str(array_amin), str(array_amax), str(mean)) more_body += '3-sigma: %s <br>' % str(sigma3) more_body += '3-sigma upper bound: %s | 3-sigma lower bound: %s <br></font>' % ( str(sigma3_upper_bound), str(sigma3_lower_bound)) more_body += '<h3><font color="black">Redis data at FULL_DURATION</font></h3><br>' more_body += '<div dir="ltr">:%s<br></div>' % redis_img_tag more_body += '<font color="black">To disable the Redis data graph view, set PLOT_REDIS_DATA to False in your settings.py, if the Graphite graph is sufficient for you,<br>' more_body += 'however do note that will remove the 3-sigma and mean value too.</font>' more_body += '<br>' more_body += '<div dir="ltr" align="right"><font color="#dd3023">Sky</font><font color="#6698FF">line</font><font color="black"> version :: %s</font></div><br>' % str(skyline_version) except: logger.error('error :: alert_smtp - could not build body') logger.info(traceback.format_exc()) for recipient in recipients: try: # @modified 20170823 - Bug #2142: 7bit SMTP encoding breaking long urls # Broke body into body and more_body to workaround the 990 character # limit per line for SMTP, using mixed as alternative indicates that # the client should select one of the parts for display and ignore # the rest (tripleee - https://stackoverflow.com/a/35115938) # msg = MIMEMultipart('alternative') msg = MIMEMultipart('mixed') # @added 20170812 - Bug #2142: 7bit SMTP encoding breaking long urls # set email charset and email encodings cs_ = charset.Charset('utf-8') cs_.header_encoding = charset.QP cs_.body_encoding = charset.QP msg.set_charset(cs_) msg['Subject'] = '[Skyline alert] - %s ALERT - %s' % (context, metric[1]) msg['From'] = sender msg['To'] = recipient msg.attach(MIMEText(body, 'html')) # @added 20170823 - Bug #2142: 7bit SMTP encoding breaking long urls # Broke body into body and more_body to workaround the 990 character # limit per line for SMTP msg.attach(MIMEText(more_body, 'html')) msg.replace_header('content-transfer-encoding', 'quoted-printable') if image_data is not None: try: msg_attachment = MIMEImage(image_data) msg_attachment.add_header('Content-ID', '<%s>' % content_id) msg.attach(msg_attachment) if settings.ENABLE_DEBUG or LOCAL_DEBUG: logger.info('debug :: alert_smtp - msg_attachment - Graphite img source done') except: logger.error('error :: alert_smtp - msg_attachment') logger.info(traceback.format_exc()) if redis_image_data: try: buf.seek(0) msg_plot_attachment = MIMEImage(buf.read()) msg_plot_attachment.add_header('Content-ID', '<%s>' % redis_graph_content_id) msg.attach(msg_plot_attachment) if settings.ENABLE_DEBUG or LOCAL_DEBUG: logger.info('debug :: alert_smtp - msg_plot_attachment - redis data done') except: logger.error('error :: alert_smtp - msg_plot_attachment') logger.info(traceback.format_exc()) except: logger.error('error :: alert_smtp - could not attach') logger.info(traceback.format_exc()) s = SMTP('127.0.0.1') try: s.sendmail(sender, recipient, msg.as_string()) if settings.ENABLE_DEBUG or LOCAL_DEBUG: logger.info('debug :: alert_smtp - message sent to %s OK' % str(recipient)) except: logger.error('error :: alert_smtp - could not send email to %s' % str(recipient)) logger.info(traceback.format_exc()) s.quit() if LOCAL_DEBUG: logger.info('debug :: alert_smtp - Memory usage after email: %s (kb)' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss) return
def send_mail(uname, uemail): strSmtp = "smtp.gmail.com:587" #主機 strAccount = "*****@*****.**" #帳號 strPassword = "******" #密碼 content = '<p>歡迎成為克里斯美食中心會員,請利用下列網址進行認證後即可使用服務: </p> <a href="http://127.0.0.1:8000/index/' + uname + '"' + '> 我要認證!</a>' #郵件內容 msg = MIMEText(content, "html", "utf-8") msg["Subject"] = "克里斯美食中心-認證信" #郵件標題 mailto = uemail #收件者 #mailto = ["收件者電子郵件"] #收件者 #mailto = ["收件者電子郵件一", "收件者電子郵件二"] server = SMTP(strSmtp) #建立SMTP連線 server.ehlo() #跟主機溝通 server.starttls() #TTLS安全認證 try: server.login(strAccount, strPassword) #登入 server.sendmail(strAccount, mailto, msg.as_string()) #寄信 hint = "郵件已發送!" except SMTPAuthenticationError: hint = "無法登入!" except: hint = "郵件發送產生錯誤!" server.quit() #關閉連線
def test_mock_patch(smtpd): with SMTP(smtpd.hostname, smtpd.port) as client: client.helo() code, repl = client.docmd("DATA", "") assert code == 530 assert repl.startswith(b"5.7.0 Authentication required")
#!/usr/bin/env python from smtplib import SMTP import sys mailFrom = '*****@*****.**' mailSubject = sys.argv[1] + '\n' mailTo = sys.argv[2] mailBody = ['Correo enviado desde la terminal de linux'] mensaje = [ 'From: ' + mailFrom, 'To: ' + mailTo, 'Subject: ' + mailSubject, '\r\n'.join(mailBody) ] mensaje = '\r\n'.join(mensaje) s = SMTP('smtp.gmail.com') s.starttls() # Si usas TLS s.ehlo() s.login('ing.rocioflores', '') # s.sendmail(mailFrom, mailTo, mensaje) s.quit()