def send_alarm_mail(ip_target, ping_loss): curl_dir = os.path.split(os.path.realpath(__file__))[0] db_file = os.path.join(curl_dir, "p_a_t.db") con = sqlite3.connect(db_file) cur = con.cursor() sql_select = "select * from smtp_server where active=1" cur.execute(sql_select) smtp_info = cur.fetchone() if smtp_info: mail = Mail(smtp_info[1], port=smtp_info[2], username=smtp_info[3], password=smtp_info[4], use_ssl=True, fromaddr=smtp_info[3]) msg = Message("[Alarm]{} loss {}%".format(ip_target, ping_loss)) receivers = [] for i in smtp_info[6].split(","): receivers.append(i) msg.to = receivers msg.body = "" with open("{}.txt".format(ip_target)) as f: for i in f.readlines(): msg.body += i mail.send(msg) print("Alarm mail send successful.Receivers are :{}".format(receivers)) else: print("There's no active SMTP server,can't send alarm mail.")
class EMail: def __init__(self): self.mail = Mail(host='smtp.gmail.com', port=465, username='******', password='******', use_tls=False, use_ssl=True, debug_level=True) def createMail(self, name, comment, email): msg = Message() sub = 'Comment From dh314Blog ' msg.fromaddr = ('Đường Hạo', '*****@*****.**') msg.subject = sub contentE = 'Bạn nhận được một comments từ dh314Blog \n Từ: ' + str( name) + '\nEmail: ' + str(email) + '\nNội dung: ' + str(comment) msg.body = contentE msg.to = '*****@*****.**' return msg def sendMail(self, name, comment, email): msg = self.createMail(name, comment, email) self.mail.send(msg) return 'Gửi thành công'
class EmailLogger(object): def __init__(self, config): user = config.get_option(CFG_KEY, CFG_USER) password = config.get_option(CFG_KEY, CFG_PASSWORD) host = config.get_option(CFG_KEY, CFG_HOST) port = config.get_option(CFG_KEY, CFG_PORT, optional=True)\ or DEFAULT_PORT tls = config.get_option(CFG_KEY, CFG_TLS, optional=True) or DEFAULT_TLS ssl = config.get_option(CFG_KEY, CFG_SSL, optional=True) or DEFAULT_SSL self.to = config.get_option(CFG_KEY, CFG_TO, optional=False) self.sender = config.get_option(CFG_KEY, CFG_SENDER, optional=False) self.messages = list() self.mail = Mail( host, port=port, username=user, password=password, use_tls=tls, use_ssl=ssl, debug_level=None ) def log(self, message): self.messages.append(message) def close(self): body = "\n".join(self.messages) self.mail.send_message( SUBJECT, fromaddr=self.sender, to=self.to, body=body )
def send_mail(srv_name): '''发送邮件''' data = request.get_json() if srv_name not in config: logging.warning('!!!'+str(datetime.datetime.now())+'InvalidService!!!') return jsonify({"status":1, "msg":"InvalidService"}) else: srv_config = config[srv_name] if not verify_key(srv_name, data['key']): logging.warning('!!!'+str(datetime.datetime.now())+'InvalidKey!!!') return jsonify({"status":1, "msg":"InvalidKey"}) mail_msg = Message(data['mail_title'], fromaddr=srv_config['mail_from'], to=data['mail_to']) mail_msg.html = data['mail_html'] mail = Mail( srv_config['smtp'], port=srv_config['port'], username=srv_config['mail_from'], password=srv_config['smtppass'], use_tls=srv_config['tls'], use_ssl=srv_config['ssl'], debug_level=None ) try: logging.info('--------'+str(datetime.datetime.now())+'--------------') logging.info(data['mail_title']) logging.info(data['mail_to']) logging.info(data['mail_html']) logging.info('=======================================================') mail.send(mail_msg) return jsonify({"status":0, "msg":"Success"}) except Exception as e: logging.warning('!!!'+str(datetime.datetime.now())+'!!!') logging.warning(str(e)) return jsonify({"status":2, "msg":str(e)})
def send(text, subject=None, toAdd=None, cc=None, log_file=None): mail_info = config.config_dic['mail_info'] sslPort = 465 server = mail_info.get('server') user = mail_info.get('user') passwd = mail_info.get('password') if not (server and user and passwd): print('Invalid login info, exit!') return mail = Mail(server, port=sslPort, username=user, password=passwd, use_tls=False, use_ssl=True, debug_level=None) msg = Message(subject) msg.fromaddr = (user, user) msg.to = toAdd if cc: msg.cc = cc if log_file: zip_path = '/tmp/build.log.zip' zip_file(log_file, zip_path) with open(zip_path, encoding='ISO-8859-1') as f: attachment = Attachment("build.log.zip", "application/octet-stream", f.read()) msg.attach(attachment) msg.body = text msg.charset = "utf-8" mail.send(msg)
def run(arguments): if arguments['--config'] or (not os.path.isfile(CONF)): conf() with open(CONF, 'rb') as f: smtp = json.loads(f.read()) mail = Mail(host=smtp['server'], username=smtp['user'], password=smtp['password'], port=int(smtp['port']), fromaddr=smtp['from']) msg = Message(arguments['--subject'], fromaddr=smtp['from'], body=arguments['--message']) to = arguments['--to'] if to: msg.to = to.split(';') cc = arguments['--cc'] if cc: msg.cc = cc.split(';') bcc = arguments['--bcc'] if bcc: msg.bcc = bcc.split(';') atta = arguments['--attach'] if atta: msg.attach(atta.split(';')) mail.send(msg)
def send(text, subject=None, cc=None, toAdd=None, log_file=None): mail_info = config.config_dic['mail_info'] sslPort = 465 server = mail_info.get('server') user = mail_info.get('user') passwd = mail_info.get('password') if not (server and user and passwd): print('Invalid login info, exit!') return mail = Mail(server, port=sslPort, username=user, password=passwd, use_tls=False, use_ssl=True, debug_level=None) msg = Message(subject) msg.fromaddr = (user, user) msg.to = toAdd if cc: msg.cc = cc if log_file: with open(log_file) as f: attachment = Attachment("build.log", "text/plain", f.read()) msg.attach(attachment) msg.body = text msg.charset = "utf-8" mail.send(msg)
def __init__(self): self.mail = Mail(host='smtp.gmail.com', port=465, username='******', password='******', use_tls=False, use_ssl=True, debug_level=True)
def send_email(): try: data = app.current_request.json_body # print(data) email = data["email"] password = data["password"] smtp_server = data["smtp_server"] smtp_port = data["smtp_port"] toAddress = data["toAddress"] fromAddress = data["fromAddress"] name = data["name"] subject = data["subject"] bodyPLAIN = data["bodyPLAIN"] bodyHTML = textile(bodyPLAIN) mail = Mail(host=smtp_server, port=smtp_port, username=email, password=password, use_ssl=True) msg = Message() msg.subject = subject msg.fromaddr = (name, fromAddress) msg.to = toAddress msg.body = bodyPLAIN msg.html = bodyHTML # msg.cc = "*****@*****.**" # msg.bcc = ["*****@*****.**", "*****@*****.**"] # msg.reply_to = "*****@*****.**" msg.date = int(round(time.time())) msg.charset = "utf-8" msg.extra_headers = {} msg.mail_options = [] msg.rcpt_options = [] # print(msg) # print(type(msg)) mail.send(msg) return Response(body={'sent': True}, status_code=200, headers=custom_headers) except Exception as error: # print("Send Emails Error") # print(error) return Response(body={'AppError': str(error)}, status_code=500, headers=custom_headers)
def sendMail(to, subject, msgContext): pLog("Send Server Mail") config = ConfigParser.RawConfigParser() config.read('defaults.cfg') msg = Message(subject, fromaddr=config.get('SendAbuse', 'from'), to=to) if(to!=config.get('SendAbuse', 'from')): msg.bcc = config.get('SendAbuse', 'from') msg.body = msgContext msg.date = time.time() msg.charset = "utf-8" mail = Mail(config.get('SendAbuse', 'server'), port=config.get('SendAbuse', 'port'), username=config.get('SendAbuse', 'user'), password=config.get('SendAbuse', 'pass'),use_tls=False, use_ssl=False, debug_level=None) mail.send(msg)
def send_message(subject, to, body): mail = Mail(MAIL_SMTP_ADDRESS, port=MAIL_PORT, username=FROM_EMAIL, password=MAIL_PASSWORD, use_tls=False, use_ssl=False, debug_level=None) msg = Message() msg = Message(subject) msg.fromaddr = (FROM_NAME, FROM_EMAIL) msg.to = to msg.bcc = [DEV_EMAIL] msg.html = body mail.send(msg) return True
def __init__(self): fr = open('./config/config.yml', 'r') config = yaml.load(fr) if 'download_status_scanner' in config['task']: scan_time = '22:00' scan_time_format = '%H:%M' if 'scan_time' in config['task']['download_status_scanner'] and\ config['task']['download_status_scanner']['scan_time'] is not None: scan_time = config['task']['download_status_scanner']['scan_time'] if 'scan_time_format' in config['task']['download_status_scanner'] and\ config['task']['download_status_scanner']['scan_time_format'] is not None: scan_time_format = config['task']['download_status_scanner']['scan_time_format'] self.scan_time = datetime.strptime(scan_time, scan_time_format) self.scanner_running = False self.last_scan_date = None # mail instance self.mail_config = config['mail'] self.mail = Mail(self.mail_config['mail_server'], port=self.mail_config['mail_port'], username=self.mail_config['mail_username'], password=self.mail_config['mail_password'], use_tls=self.mail_config['mail_use_tls'], use_ssl=self.mail_config['mail_use_ssl']) self.mail.fromaddr = ('Download Alert', self.mail_config['mail_default_sender']) # root path of site self.root_path = '{0}://{1}'.format(config['site']['protocol'], config['site']['host']) # mail template # tfr = open('./templates/download-status-alert.html', 'r') env = Environment( loader=FileSystemLoader('./templates') ) self.mail_template = env.get_template('download-status-alert.html')
def sendMail(to, subject, msgContext): pLog("Send Server Mail") config = ConfigParser.RawConfigParser() config.read('defaults.cfg') msg = Message(subject, fromaddr=config.get('SendAbuse', 'from'), to=to) if (to != config.get('SendAbuse', 'from')): msg.bcc = config.get('SendAbuse', 'from') msg.body = msgContext msg.date = time.time() msg.charset = "utf-8" mail = Mail(config.get('SendAbuse', 'server'), port=config.get('SendAbuse', 'port'), username=config.get('SendAbuse', 'user'), password=config.get('SendAbuse', 'pass'), use_tls=False, use_ssl=False, debug_level=None) mail.send(msg)
def send(text, subject, toAdd, cc=None, attachments=None): """邮件发送方法 Arguments: text {str} -- 邮件内容,可以为字符串或者 HTML 字符串 subject {str} -- 邮件标题 toAdd {list} -- 收件人列表 Keyword Arguments: cc {list} -- 抄送人列表 (default: {None}) attachments {list} -- 附件列表,示例:[{'path': '/path/to/file', 'file_name': '附件文件名'}] (default: {None}) """ assert subject is not None assert toAdd is not None sslPort = os.getenv('MAIL_SERVER_PORT') server = os.getenv('MAIL_SMTP_SERVER') user = os.getenv('MAIL_USER') passwd = os.getenv('MAIL_PASSWORD') assert server is not None assert user is not None assert passwd is not None if not sslPort: sslPort = 465 mail = Mail(server, port=sslPort, username=user, password=passwd, use_tls=False, use_ssl=True, debug_level=None) msg = Message(subject) msg.fromaddr = (user, user) msg.to = toAdd if cc: msg.cc = cc if attachments: for att in attachments: with open(att['path'], 'rb') as f: mail_attachment = Attachment(att['file_name'], "application/octet-stream", f.read()) msg.attach(mail_attachment) msg.html = text msg.charset = "utf-8" mail.send(msg)
def send_mail(subject, to, content, cc=None, type='plain', system='自动'): if cc is None: cc = [] html, body = None, None if type == 'html': html = content else: body = content subject = subject.replace('\n', ' ') subject = '[{}]{}'.format(system, subject) mail = Mail(host=host, port=25, username=sender, password=password) msg = Message(subject=subject, to=to, cc=cc, html=html, body=body, fromaddr=sender) mail.send(msg)
def __init__(self): fr = open('./config/config.yml', 'r') config = yaml.load(fr) if 'download_status_scanner' in config['task']: scan_time = '22:00' scan_time_format = '%H:%M' if 'scan_time' in config['task']['download_status_scanner'] and\ config['task']['download_status_scanner']['scan_time'] is not None: scan_time = config['task']['download_status_scanner'][ 'scan_time'] if 'scan_time_format' in config['task']['download_status_scanner'] and\ config['task']['download_status_scanner']['scan_time_format'] is not None: scan_time_format = config['task']['download_status_scanner'][ 'scan_time_format'] self.scan_time = datetime.strptime(scan_time, scan_time_format) self.scanner_running = False self.last_scan_date = None # mail instance self.mail_config = config['mail'] self.mail = Mail(self.mail_config['mail_server'], port=self.mail_config['mail_port'], username=self.mail_config['mail_username'], password=self.mail_config['mail_password'], use_tls=self.mail_config['mail_use_tls'], use_ssl=self.mail_config['mail_use_ssl']) self.mail.fromaddr = ('Download Alert', self.mail_config['mail_default_sender']) # root path of site self.root_path = '{0}://{1}'.format(config['site']['protocol'], config['site']['host']) # mail template # tfr = open('./templates/download-status-alert.html', 'r') env = Environment(loader=FileSystemLoader('./templates')) self.mail_template = env.get_template('download-status-alert.html')
def __init__(self, config): user = config.get_option(CFG_KEY, CFG_USER) password = config.get_option(CFG_KEY, CFG_PASSWORD) host = config.get_option(CFG_KEY, CFG_HOST) port = config.get_option(CFG_KEY, CFG_PORT, optional=True)\ or DEFAULT_PORT tls = config.get_option(CFG_KEY, CFG_TLS, optional=True) or DEFAULT_TLS ssl = config.get_option(CFG_KEY, CFG_SSL, optional=True) or DEFAULT_SSL self.to = config.get_option(CFG_KEY, CFG_TO, optional=False) self.sender = config.get_option(CFG_KEY, CFG_SENDER, optional=False) self.messages = list() self.mail = Mail( host, port=port, username=user, password=password, use_tls=tls, use_ssl=ssl, debug_level=None )
def send_mail(smtp_user, smtp_pass, subject='test', body='test', sendto=sendto, smtp_server='smtp.qq.com', smtp_port=465): mail = Mail(smtp_server, port=smtp_port, username=smtp_user, password=smtp_pass, use_tls=False, use_ssl=True, debug_level=None) mail.send_message(subject, fromaddr=smtp_user, to=sendto, body=body)
# Grab the list of link of pictures for a in doc.find_class('filename-link'): last_pictures.add(a.attrib['href']) # Build a set of mot seen pictures. The last pictures list - the saved pictures list pictures_not_seen = last_pictures - pictures_seen if len(pictures_not_seen) == 0: print("No new pictures. Exiting") else: # Send an email containing the URL of the new pictures mail = Mail(config['smtp']['host'], port = int(config['smtp']['port']), username = config['smtp']['username'], password = config['smtp']['password'], use_tls = config['smtp']['use_tls'], use_ssl = config['smtp']['use_ssl']) body = "<p>A new picture has been posted !</p>" for picture in pictures_not_seen: body += "- <a href='%s'>%s</a><br>" % (picture, picture) mail.send_message("New pictures of %s" % dp['name'], fromaddr=dp['from'], bcc=dp['to'], html=body) # Save the last pictures seen to the backup file with open(backup_file, 'w') as f: f.write(json.dumps(list(last_pictures), indent=4))
def send_email(to_email, subject, body): if 'SMTP_LOGIN' in os.environ and 'SMTP_PASSWORD' in os.environ: mail = Mail("fiq.de", port=25, username=os.environ['SMTP_LOGIN'], password=os.environ['SMTP_PASSWORD'], use_tls=False, use_ssl=False, debug_level=None) mail.send_message(subject, fromaddr="*****@*****.**", to=to_email, body=body) else: print('Cannot send email. SMTP_LOGIN and SMTP_PASSWORD not set.')
pwrd = os.environ['GMAIL_PASS'] if __name__ == "__main__": with Imbox(imap, username=user, password=pwrd, ssl=True, ssl_context=None, starttls=False) as imbox: drafts = imbox.messages(folder="[Gmail]/Drafts") todays_mail = [] for uid, msg in drafts: if 'schedmail' in msg.subject.lower(): date = msg.subject.lower().split(':')[1] today = pendulum.now().date().isoformat() subject_date = pendulum.parse(date).date().isoformat() if subject_date == today: todays_mail.append(msg) mail = Mail('smtp.gmail.com', port=587, username=user, password=pwrd, use_tls=True) for i in todays_mail: msg = Message(i.subject.split(':')[-1]) msg.fromaddr = (i.sent_from[0]['name'], i.sent_from[0]['email']) msg.to = [j['email'] for j in i.sent_to] msg.cc = [j['email'] for j in i.cc] msg.bcc = [j['email'] for j in i.bcc] msg.body = i.body['plain'][0] msg.html = i.body['html'][0] msg.charset = 'utf-8' mail.send(msg)
class DownloadStatusScanner: def __init__(self): fr = open('./config/config.yml', 'r') config = yaml.load(fr) if 'download_status_scanner' in config['task']: scan_time = '22:00' scan_time_format = '%H:%M' if 'scan_time' in config['task']['download_status_scanner'] and\ config['task']['download_status_scanner']['scan_time'] is not None: scan_time = config['task']['download_status_scanner'][ 'scan_time'] if 'scan_time_format' in config['task']['download_status_scanner'] and\ config['task']['download_status_scanner']['scan_time_format'] is not None: scan_time_format = config['task']['download_status_scanner'][ 'scan_time_format'] self.scan_time = datetime.strptime(scan_time, scan_time_format) self.scanner_running = False self.last_scan_date = None # mail instance self.mail_config = config['mail'] self.mail = Mail(self.mail_config['mail_server'], port=self.mail_config['mail_port'], username=self.mail_config['mail_username'], password=self.mail_config['mail_password'], use_tls=self.mail_config['mail_use_tls'], use_ssl=self.mail_config['mail_use_ssl']) self.mail.fromaddr = ('Download Alert', self.mail_config['mail_default_sender']) # root path of site self.root_path = '{0}://{1}'.format(config['site']['protocol'], config['site']['host']) # mail template # tfr = open('./templates/download-status-alert.html', 'r') env = Environment(loader=FileSystemLoader('./templates')) self.mail_template = env.get_template('download-status-alert.html') def start(self): lc = LoopingCall(self.check_time) lc.start(60) def check_time(self): if self.scanner_running: return current_time = datetime.utcnow() logger.debug(current_time) if self.last_scan_date is not None and self.last_scan_date == current_time.date( ): return if (not self.scanner_running) and (self.scan_time.hour == current_time.hour): self.scanner_running = True self.scan_download_status() self.last_scan_date = current_time.date() self.scanner_running = False def scan_download_status(self): threads.deferToThread(self.__scan_download_status_in_thread) def __scan_download_status_in_thread(self): logger.info('start scan download status') session = SessionManager.Session() try: current_time = datetime.utcnow() result = session.query(Episode).\ options(joinedload(Episode.bangumi).joinedload(Bangumi.maintained_by)).\ filter(Episode.airdate != None).\ filter(Episode.status != Episode.STATUS_DOWNLOADED).\ filter(Episode.airdate < current_time.date()).\ filter(Bangumi.status != Bangumi.STATUS_FINISHED).\ all() admin_map = {} for episode in result: if current_time.date() - episode.airdate < timedelta( days=episode.bangumi.alert_timeout): continue bangumi_id = str(episode.bangumi_id) if episode.bangumi.maintained_by is None: if 'sys' not in admin_map: admin_map['sys'] = {} if bangumi_id not in admin_map['sys']: admin_map['sys'][bangumi_id] = { 'bangumi': episode.bangumi, 'episodes': [] } admin_map['sys'][bangumi_id]['episodes'].append(episode) else: maintainer_uid = str(episode.bangumi.maintained_by.id) if maintainer_uid not in admin_map: admin_map[maintainer_uid] = { 'user': episode.bangumi.maintained_by, 'bangumi_map': {} } if bangumi_id not in admin_map[maintainer_uid]: admin_map[maintainer_uid]['bangumi_map'][ bangumi_id] = { 'bangumi': episode.bangumi, 'episodes': [] } admin_map[maintainer_uid]['bangumi_map'][bangumi_id][ 'episodes'].append(episode) msg_list = [] for uid in admin_map: if uid == 'sys': all_admin_list = session.query(User).filter( User.level >= User.LEVEL_ADMIN).all() msg_list = msg_list + self.__send_email_to_all( all_admin_list, admin_map['sys']) elif admin_map[uid]['user'].email is None or not admin_map[ uid]['user'].email_confirmed: continue else: msg_list.append( self.__send_email_to(admin_map[uid]['user'], admin_map[uid]['bangumi_map'])) self.mail.send(msg_list) except exc.DBAPIError as db_error: logger.error(db_error, exc_info=True) # if connection is invalid rollback the session if db_error.connection_invalidated: session.rollback() finally: SessionManager.Session.remove() def __send_email_to(self, user, bangumi_map): info = { 'username': user.name, 'root_path': self.root_path, 'sys': False } bangumi_list = self.__bangumi_map_to_list(bangumi_map) msg = Message('Download Status Alert', fromaddr=('Alert System', self.mail_config['mail_default_sender'])) msg.to = user.email msg.html = self.mail_template.render(info=info, bangumi_list=bangumi_list) return msg def __send_email_to_all(self, admin_list, bangumi_map): msg_list = [] for user in admin_list: info = { 'username': user.name, 'root_path': self.root_path, 'sys': True } bangumi_list = self.__bangumi_map_to_list(bangumi_map) msg = Message('Download Status Alert', fromaddr=('Alert System', self.mail_config['mail_default_sender'])) msg.to = user.email msg.html = self.mail_template.render(info=info, bangumi_list=bangumi_list) msg_list.append(msg) return msg_list def __bangumi_map_to_list(self, bangumi_map): bangumi_list = [] for bangumi_id in bangumi_map: bangumi = { 'id': bangumi_id, 'name': bangumi_map[bangumi_id]['bangumi'].name, 'episodes': [] } for episode in bangumi_map[bangumi_id]['episodes']: eps = { 'episode_no': episode.episode_no, 'airdate': episode.airdate } bangumi['episodes'].append(eps) bangumi['episodes'].sort(key=lambda e: e['airdate']) bangumi_list.append(bangumi) return bangumi_list
class DownloadStatusScanner: def __init__(self): fr = open('./config/config.yml', 'r') config = yaml.load(fr) if 'download_status_scanner' in config['task']: scan_time = '22:00' scan_time_format = '%H:%M' if 'scan_time' in config['task']['download_status_scanner'] and\ config['task']['download_status_scanner']['scan_time'] is not None: scan_time = config['task']['download_status_scanner']['scan_time'] if 'scan_time_format' in config['task']['download_status_scanner'] and\ config['task']['download_status_scanner']['scan_time_format'] is not None: scan_time_format = config['task']['download_status_scanner']['scan_time_format'] self.scan_time = datetime.strptime(scan_time, scan_time_format) self.scanner_running = False self.last_scan_date = None # mail instance self.mail_config = config['mail'] self.mail = Mail(self.mail_config['mail_server'], port=self.mail_config['mail_port'], username=self.mail_config['mail_username'], password=self.mail_config['mail_password'], use_tls=self.mail_config['mail_use_tls'], use_ssl=self.mail_config['mail_use_ssl']) self.mail.fromaddr = ('Download Alert', self.mail_config['mail_default_sender']) # root path of site self.root_path = '{0}://{1}'.format(config['site']['protocol'], config['site']['host']) # mail template # tfr = open('./templates/download-status-alert.html', 'r') env = Environment( loader=FileSystemLoader('./templates') ) self.mail_template = env.get_template('download-status-alert.html') def start(self): lc = LoopingCall(self.check_time) lc.start(60) def check_time(self): if self.scanner_running: return current_time = datetime.utcnow() logger.debug(current_time) if self.last_scan_date is not None and self.last_scan_date == current_time.date(): return if (not self.scanner_running) and (self.scan_time.hour == current_time.hour): self.scanner_running = True self.scan_download_status() self.last_scan_date = current_time.date() self.scanner_running = False def scan_download_status(self): threads.deferToThread(self.__scan_download_status_in_thread) def __scan_download_status_in_thread(self): logger.info('start scan download status') session = SessionManager.Session() try: current_time = datetime.utcnow() result = session.query(Episode).\ options(joinedload(Episode.bangumi).joinedload(Bangumi.maintained_by)).\ filter(Episode.airdate != None).\ filter(Episode.status != Episode.STATUS_DOWNLOADED).\ filter(Episode.airdate < current_time.date()).\ filter(Bangumi.status != Bangumi.STATUS_FINISHED).\ all() admin_map = {} for episode in result: if current_time.date() - episode.airdate < timedelta(days=episode.bangumi.alert_timeout): continue bangumi_id = str(episode.bangumi_id) if episode.bangumi.maintained_by is None: if 'sys' not in admin_map: admin_map['sys'] = {} if bangumi_id not in admin_map['sys']: admin_map['sys'][bangumi_id] = { 'bangumi': episode.bangumi, 'episodes': [] } admin_map['sys'][bangumi_id]['episodes'].append(episode) else: maintainer_uid = str(episode.bangumi.maintained_by.id) if maintainer_uid not in admin_map: admin_map[maintainer_uid] = { 'user': episode.bangumi.maintained_by, 'bangumi_map': {} } if bangumi_id not in admin_map[maintainer_uid]: admin_map[maintainer_uid]['bangumi_map'][bangumi_id] = { 'bangumi': episode.bangumi, 'episodes': [] } admin_map[maintainer_uid]['bangumi_map'][bangumi_id]['episodes'].append(episode) msg_list = [] for uid in admin_map: if uid == 'sys': all_admin_list = session.query(User).filter(User.level >= User.LEVEL_ADMIN).all() msg_list = msg_list + self.__send_email_to_all(all_admin_list, admin_map['sys']) elif admin_map[uid]['user'].email is None or not admin_map[uid]['user'].email_confirmed: continue else: msg_list.append(self.__send_email_to(admin_map[uid]['user'], admin_map[uid]['bangumi_map'])) self.mail.send(msg_list) except exc.DBAPIError as db_error: logger.error(db_error, exc_info=True) # if connection is invalid rollback the session if db_error.connection_invalidated: session.rollback() finally: SessionManager.Session.remove() def __send_email_to(self, user, bangumi_map): info = { 'username': user.name, 'root_path': self.root_path, 'sys': False } bangumi_list = self.__bangumi_map_to_list(bangumi_map) msg = Message('Download Status Alert', fromaddr=('Alert System', self.mail_config['mail_default_sender'])) msg.to = user.email msg.html = self.mail_template.render(info=info, bangumi_list=bangumi_list) return msg def __send_email_to_all(self, admin_list, bangumi_map): msg_list = [] for user in admin_list: info = { 'username': user.name, 'root_path': self.root_path, 'sys': True } bangumi_list = self.__bangumi_map_to_list(bangumi_map) msg = Message('Download Status Alert', fromaddr=('Alert System', self.mail_config['mail_default_sender'])) msg.to = user.email msg.html = self.mail_template.render(info=info, bangumi_list=bangumi_list) msg_list.append(msg) return msg_list def __bangumi_map_to_list(self, bangumi_map): bangumi_list = [] for bangumi_id in bangumi_map: bangumi = { 'id': bangumi_id, 'name': bangumi_map[bangumi_id]['bangumi'].name, 'episodes': [] } for episode in bangumi_map[bangumi_id]['episodes']: eps = { 'episode_no': episode.episode_no, 'airdate': episode.airdate } bangumi['episodes'].append(eps) bangumi['episodes'].sort(key=lambda e: e['airdate']) bangumi_list.append(bangumi) return bangumi_list
from sender import Mail, Message from .config import config email_conf = {} for setting in ('host', 'port', 'username', 'password', 'use_tls', 'use_ssl'): email_conf[setting] = config['email'][setting] MAIL = Mail(**email_conf) if 'from_pretty' in config['email']: MAIL.fromaddr = (config['email']['from_pretty'], config['email']['from_address']) else: MAIL.fromaddr = config['email']['from_address'] def send_jobs(jobs): "Send an email notifying of current jobs" msg = Message( config['email']['subject'].format(n=len(jobs)), to=config['email_address'], ) msg.body = "Found {n} potential jobs:\n\n" for idx, job in enumerate(jobs): idx += 1 msg.body += "{}. {}\n\n\n".format(idx, job.to_string()) MAIL.send(msg)
#!/bin/python # coding=utf-8 from sender import Mail, Message import time import os mail = Mail( "smtp.abc.com", port = 587, username = "******", password = "******", use_tls = True, debug_level = True ) url='' today=time.strftime("%d_%m_%Y") for i in os.listdir('folder'): if today in i: url= 'http://*****:*****@abc.com") msg.to = "*****@*****.**" msg.html = "<p> Dear <br>Today is %s<br><a href=%s>%s</a>" %(today,url,url) msg.extra_headers = {} msg.mail_options = [] msg.rcpt_options = [] # Send message
~~~~~~~ Demo simple SMTP mail. :copyright: (c) 2014 by Shipeng Feng. :license: BSD, see LICENSE for more details. """ from sender import Mail, Message, Attachment SMTP_HOST = 'smtp.example.com' SMTP_USER = '******' SMTP_PASS = '******' SMTP_ADDRESS = '*****@*****.**' mail = Mail(host=SMTP_HOST, username=SMTP_USER, password=SMTP_PASS, fromaddr=SMTP_ADDRESS) msg01 = Message("Hello01", to="*****@*****.**", body="hello world") msg02 = Message("Hello02", to="*****@*****.**") msg02.fromaddr = ('no-reply', '*****@*****.**') msg02.body = "hello world!" msg03 = Message("Hello03", to="*****@*****.**") msg03.fromaddr = (u'请勿回复', '*****@*****.**') msg03.body = u"你好世界" # Chinese :) msg03.html = u"<b>你好世界</b>" msg04 = Message("Hello04", body="Hello world 04") msg04.to = "*****@*****.**"
Demo simple SMTP mail. :copyright: (c) 2014 by Shipeng Feng. :license: BSD, see LICENSE for more details. """ from sender import Mail, Message, Attachment SMTP_HOST = 'smtp.example.com' SMTP_USER = '******' SMTP_PASS = '******' SMTP_ADDRESS = '*****@*****.**' mail = Mail(host=SMTP_HOST, username=SMTP_USER, password=SMTP_PASS, fromaddr=SMTP_ADDRESS) msg01 = Message("Hello01", to="*****@*****.**", body="hello world") msg02 = Message("Hello02", to="*****@*****.**") msg02.fromaddr = ('no-reply', '*****@*****.**') msg02.body = "hello world!" msg03 = Message("Hello03", to="*****@*****.**") msg03.fromaddr = (u'请勿回复', '*****@*****.**') msg03.body = u"你好世界" # Chinese :) msg03.html = u"<b>你好世界</b>"
smtp_port = 25 smtp_username = "" smtp_password = "" smtp_security = "SSL" #END SETTINGS input = sys.stdin.read() text = mime.from_string(input) msg = Message(text.headers['subject']) msg.fromaddr = text.headers['from'] msg.to = text.headers['to'] msg.body = text.body msg.date = time.time() msg.charset = "utf-8" #Check SSL or TLS smtp_ssl_use = False smtp_tls_use = False if smtp_security == "SSL": smtp_ssl_use = True elif smtp_security == "TLS": smtp_tls_use = True else: smtp_ssl_use = False smtp_tls_use = False mail = Mail(smtp_hostname, port=smtp_port, username=smtp_username, password=smtp_password, use_tls=smtp_tls_use, use_ssl=smtp_ssl_use, debug_level = None) mail.send(msg)
#!/usr/bin/env python3 # Before begin you need to change Gmail settings: # 1. Turn off 2-step verification # 2. Enable: Allow less secure apps from sender import Mail, Message mail = Mail("smtp.gmail.com", port=587, username="******", password="******", use_tls=True, use_ssl=False, debug_level=None) mail.fromaddr = ("Sender Name", "*****@*****.**") msg = Message("msg subject") msg.fromaddr = ("Sender Name", "*****@*****.**") msg.to = "*****@*****.**" msg.body = "this is a msg plain text body" msg.html = "<b>this is a msg text body</b>" msg.reply_to = "*****@*****.**" msg.charset = "utf-8" msg.extra_headers = {} msg.mail_options = [] msg.rcpt_options = [] # Send message mail.send(msg)