本文整理汇总了Python中email.utils.COMMASPACE.join方法的典型用法代码示例。如果您正苦于以下问题:Python COMMASPACE.join方法的具体用法?Python COMMASPACE.join怎么用?Python COMMASPACE.join使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类email.utils.COMMASPACE
的用法示例。
在下文中一共展示了COMMASPACE.join方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: send_mail_by_postfix
# 需要导入模块: from email.utils import COMMASPACE [as 别名]
# 或者: from email.utils.COMMASPACE import join [as 别名]
def send_mail_by_postfix(mail_to, content_type, content,
subject=DEFAULT_EMAIL_NOTIFY_SUBJECT,
mail_from=EMAIL_NOTIFY_NAME,
server=EMAIL_SMTP_SERVER):
"""
使用 Postfix 作为 SMTP Server 来发送邮件
"""
logger.debug('run send_mail_by_postfix')
if type(mail_to) != list:
raise TypeError('mail_to is not a list')
if content_type not in ('plain', 'html'):
raise ValueError('content_type is not plain or html')
msg = MIMEMultipart()
msg['From'] = mail_from
msg['To'] = COMMASPACE.join(mail_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(MIMEText(content, _subtype=content_type, _charset='utf-8'))
smtp = smtplib.SMTP(server)
smtp.sendmail(mail_from, mail_to, msg.as_string())
smtp.close()
logger.info('邮件发送成功')
示例2: update_user_resource
# 需要导入模块: from email.utils import COMMASPACE [as 别名]
# 或者: from email.utils.COMMASPACE import join [as 别名]
def update_user_resource(username, resource):
with flask.current_app.db.session as session:
user = find_user(username, session)
if not user.application:
raise UserError("User haven't started the application")
resources = set(user.application.resources_granted or [])
resources.add(resource)
user.application.resources_granted = list(resources)
if "EMAIL_SERVER" in config:
content = "You have been granted {} resources in Bionimbus Cloud.".format(
", ".join(resources)
)
send_mail(
config["SEND_FROM"],
[user.email],
"Account update from Bionimbus Cloud",
text=content,
server=config["EMAIL_SERVER"],
)
return get_user_info(user, session)
示例3: send_mail
# 需要导入模块: from email.utils import COMMASPACE [as 别名]
# 或者: from email.utils.COMMASPACE import join [as 别名]
def send_mail(send_from, send_to, subject, text, server, certificates=None):
assert isinstance(send_to, list)
msg = MIMEMultipart(
From=send_from, To=COMMASPACE.join(send_to), Date=formatdate(localtime=True)
)
msg["Subject"] = subject
msg.attach(MIMEText(text))
for cert in certificates or []:
application = MIMEApplication(cert.data, cert.extension)
application.add_header(
"Content-Disposition", 'attachment; filename="{}"'.format(cert.filename)
)
application.set_param("name", cert.filename)
msg.attach(application)
smtp = smtplib.SMTP(server)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()
示例4: diff_file
# 需要导入模块: from email.utils import COMMASPACE [as 别名]
# 或者: from email.utils.COMMASPACE import join [as 别名]
def diff_file(path1,path2,method=u'uniq',newline=True):
""" Shows difference between files
Returns the diff result (multi lines)
``path1``, ``path2`` are absolute paths.
"""
result = ""
with codecs.open(path1,'r','utf-8') as f: f1 = f.readlines()
with codecs.open(path2,'r','utf-8') as f: f2 = f.readlines()
if newline and len(f1) > 0 and len(f2) > 0:
f1[-1] = f1[-1]+'\n'
f2[-1] = f2[-1]+'\n'
diff = []
if method == 'context':
diff = difflib.context_diff(f1,f2,fromfile=path1,tofile=path2)
if method == 'uniq':
diff = difflib.ndiff(f1,f2)
result = ''.join(filter(lambda x: not x.startswith(' '),list(diff)))
BuiltIn().log("Compared `%s` and `%s`" % (path1,path2))
return result
示例5: cleanup_result
# 需要导入模块: from email.utils import COMMASPACE [as 别名]
# 或者: from email.utils.COMMASPACE import join [as 别名]
def cleanup_result(ignore=u'^(log.html|output.xml|report.html)$'):
""" Cleans up the result folder
Deletes all files in current active folder that does not match the
``ignore`` expression and are older than the time the test has started.
*Note*: The keyword only removes files but not folders
"""
BuiltIn().log("Delete files in result folder `%s`" % _result_folder)
candidates=[]
for root, dirs, files in os.walk(_result_folder):
for basename in files:
if not re.search(ignore,basename) and not '/.svn' in root:
file_path = os.path.join(root,basename)
modified_time = os.path.getmtime(file_path)
if modified_time < int(START_TIME.strftime('%s')):
candidates.append(file_path)
for x in candidates:
os.remove(x)
BuiltIn().log(" Deleted `%s`" % x)
BuiltIn().log("Deleted %d files in current result folder" % len(candidates))
示例6: OpenLogFile
# 需要导入模块: from email.utils import COMMASPACE [as 别名]
# 或者: from email.utils.COMMASPACE import join [as 别名]
def OpenLogFile(self):
'''Open the appropriate log file, depending on event properties and settings in .ini file.
Now, we only need to open the one file delimited logfile
'''
# do stuff only if file is closed. if it is open, we don't have to do anything at all, just return true.
if self.log == None:
# Filter out any characters that are not allowed as a windows filename, just in case the user put them into the config file
self.settings['General']['Log File'] = self.filter.sub(r'__',self.settings['General']['Log File'])
self.writeTarget = os.path.normpath(os.path.join(self.settings['General']['Log Directory'], self.settings['General']['Log File']))
try:
self.log = open(self.writeTarget, 'a')
self.PrintDebug("writing to: " + self.writeTarget)
return True
except OSError, detail:
if(detail.errno==17): #if file already exists, swallow the error
pass
else:
self.PrintDebug(str(sys.exc_info()[0]) + ", " + str(sys.exc_info()[1]) + "\n")
return False
except:
示例7: send_mail
# 需要导入模块: from email.utils import COMMASPACE [as 别名]
# 或者: from email.utils.COMMASPACE import join [as 别名]
def send_mail( send_from, send_to, subject, text, files=[], server="localhost", port=25, username='', password='', isTls=True):
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="{0}"'.format(os.path.basename(f)))
msg.attach(part)
smtp = smtplib.SMTP(server, port)
if isTls: smtp.starttls()
if len(username)>0 : smtp.login(username,password)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.quit()
示例8: download_archive
# 需要导入模块: from email.utils import COMMASPACE [as 别名]
# 或者: from email.utils.COMMASPACE import join [as 别名]
def download_archive():
md5 = request.values['md5']
# look up the details of the entry by md5
with get_db_connection('email_archive') as db:
c = db.cursor()
c.execute("SELECT s.hostname FROM archive a JOIN archive_server s ON a.server_id = s.server_id "
"WHERE a.md5 = UNHEX(%s)", (md5,))
try:
row = c.fetchone()
if row is None:
logging.error("query returned no results for md5 {}".format(md5))
raise ValueError()
except Exception as e:
logging.error("archive md5 {} does not exist".format(md5))
return "", 400
hostname = row[0]
logging.info("got hostname {} for md5 {}".format(hostname, md5))
root_archive_path = saq.CONFIG['analysis_module_email_archiver']['archive_dir']
archive_path = os.path.join(root_archive_path, hostname, md5[0:3], '{}.gz.gpg'.format(md5))
full_path = os.path.join(SAQ_HOME, archive_path)
if not os.path.exists(full_path):
logging.error("archive path {} does not exist".format(full_path))
#flash("archive path {} does not exist".format(archive_path))
return redirect(url_for('analysis.index'))
logging.info("user {} downloaded email archive {}".format(current_user, archive_path))
return send_from_directory(os.path.dirname(full_path), os.path.basename(full_path), as_attachment=True)
示例9: query_message_ids
# 需要导入模块: from email.utils import COMMASPACE [as 别名]
# 或者: from email.utils.COMMASPACE import join [as 别名]
def query_message_ids():
# if we passed a JSON formatted list of alert_uuids then we compute the message_ids from that
if 'alert_uuids' in request.values:
alert_uuids = json.loads(request.values['alert_uuids'])
message_ids = []
with get_db_connection() as db:
c = db.cursor()
c.execute("""SELECT o.value FROM observables o JOIN observable_mapping om ON o.id = om.observable_id
JOIN alerts a ON om.alert_id = a.id
WHERE o.type = 'message_id' AND a.uuid IN ( {} )""".format(','.join(['%s' for _ in alert_uuids])),
tuple(alert_uuids))
for row in c:
message_id = row[0].decode(errors='ignore')
message_ids.append(message_id)
else:
# otherwise we expect a JSON formatted list of message_ids
message_ids = json.loads(request.values['message_ids'])
import html
message_ids = [html.unescape(_) for _ in message_ids]
result = { }
for source in get_email_archive_sections():
result[source] = search_archive(source, message_ids,
excluded_emails=saq.CONFIG['remediation']['excluded_emails'].split(','))
for archive_id in result[source].keys():
result[source][archive_id] = result[source][archive_id].json
response = make_response(json.dumps(result))
response.mimetype = 'application/json'
return response
示例10: _create_email_msg
# 需要导入模块: from email.utils import COMMASPACE [as 别名]
# 或者: from email.utils.COMMASPACE import join [as 别名]
def _create_email_msg(self, to=None, subject=None, body=None):
self._to_emails = to or self._to_emails
if not self._to_emails:
raise ValueError("ERROR: no email adress to send the message to was provided.")
msg = MIMEMultipart()
msg['From'] = self._send_from
msg['To'] = COMMASPACE.join(self._to_emails)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
body = body if body else DEFAULT_BODY
msg.attach(MIMEText(body))
return msg
示例11: _send_email
# 需要导入模块: from email.utils import COMMASPACE [as 别名]
# 或者: from email.utils.COMMASPACE import join [as 别名]
def _send_email(self, msg):
try:
smtp = smtplib.SMTP(host=self._smtp_host, port=int(self._smtp_port))
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login(self._send_from, self._email_pass)
logger.info('Sending email from {} to {} ...'.format(self._send_from, ','.join(self._to_emails)))
smtp.sendmail(self._send_from, self._to_emails, msg.as_string())
logger.info('Email to {} has been succesfully sent'.format(','.join(self._to_emails)))
except Exception as e:
logger.error('Sending failed with an error: {}'.format(str(e)))
finally:
smtp.quit()
示例12: test_multi_receiver
# 需要导入模块: from email.utils import COMMASPACE [as 别名]
# 或者: from email.utils.COMMASPACE import join [as 别名]
def test_multi_receiver(self):
ctx = {}
self.send_mail_plugin.execute(
ctx,
"test",
receivers=COMMASPACE.join([
"17600817832@163.com",
"chihz3800@163.com",
"hongze.chi@gmail.com"
]),
sender="17600817832@163.com",
subject=lambda ctx, receiver: u"你好, " + receiver,
content=lambda ctx, receiver: u"你好, " + receiver
)
self.send_mail_plugin.execute(
ctx,
"test",
receivers=[
"hongze.chi@gmail.com",
"chihz3800@163.com",
],
sender="17600817832@163.com",
subject=lambda ctx, receiver: u"Hahaha, " + receiver,
content=lambda ctx, receiver: u"你好, content " + receiver,
attachments=[
Attachment(StringIO("simple!"),
"text/plain", u"文本.txt".encode("gb2312")),
Attachment(StringIO("naive!"),
"text/plain", u"文本2.txt".encode("gb2312"))
]
)
示例13: _wait_thread
# 需要导入模块: from email.utils import COMMASPACE [as 别名]
# 或者: from email.utils.COMMASPACE import join [as 别名]
def _wait_thread(*stuff):
for something in stuff: something.join()
示例14: csv_create
# 需要导入模块: from email.utils import COMMASPACE [as 别名]
# 或者: from email.utils.COMMASPACE import join [as 别名]
def csv_create(pathname, *header):
""" Create a CSV file with headers defined by a list `header`
The CSV file is opend with `UTF-8` encoding mode
"""
if sys.version_info[0] > 2:
with open(pathname, 'w', encoding='utf-8') as f:
f.write(','.join(header))
else:
with codecs.open(pathname, 'w', 'utf-8') as f:
f.write(','.join(header))
BuiltIn().log('Create an empty CSV file `%s`' % pathname)
示例15: csv_add
# 需要导入模块: from email.utils import COMMASPACE [as 别名]
# 或者: from email.utils.COMMASPACE import join [as 别名]
def csv_add(pathname, *items):
""" Add more data define by a list `items` to a existed CSV file
*Note:*: do not check the consistency between item's number and header's
number
"""
if sys.version_info[0] > 2:
with open(pathname, 'a', encoding='utf-8') as f:
f.write("\r\n")
f.write(','.join(items))
else:
with codecs.open(pathname, 'a', 'utf-8') as f:
f.write("\r\n")
f.write(','.join(items))
BuiltIn().log('Added more data to CSV file `%s`' % pathname)