def book_msg(to_addr, book):
# TODO: Give a subject.
subject = ''
mobi_workshop_dir = '../../mobi_workshop/'
bookname = book+'.mobi'
msg = MIMEMultipart()
msg['From'] = mail_config['from_addr']
msg['To'] = to_addr
msg['Subject'] = Header(subject, 'utf-8').encode()
msg.attach(MIMEText('send with file...', 'plain', 'utf-8'))
# TODO: check if target is 0kb, if so, send_alert.
with open(mobi_workshop_dir+book+'.mobi', 'rb') as f:
mime = MIMEBase('*', '*/*', filename=bookname)
mime.add_header('Content-Disposition', 'attachment', filename=bookname)
mime.add_header('Content-ID', '<0>')
mime.add_header('X-Attachment-Id', '0')
mime.set_payload(f.read())
encoders.encode_base64(mime)
msg.attach(mime)
return msg
python类MIMEMultipart()的实例源码
def send_email(self, mail_from, mail_to, subject, html_msg, cc_list=None,
plain_msg=None):
LOG.info('Sending email ....')
message = MIMEMultipart()
message['Subject'] = subject
message['to'] = mail_to
if cc_list:
message['cc'] = ', '.join(cc_list)
message['from'] = mail_from or self.notify_from
msg = MIMEText(html_msg, 'html')
message.attach(msg)
if plain_msg:
plain_msg = MIMEText(plain_msg, 'plain')
message.attach(plain_msg)
try:
self.server.sendmail(mail_from, mail_to,
message.as_string())
LOG.info('Email sent successfully !')
except Exception as e:
LOG.error(e)
def gen_msg(content, subject, attachments, nick_from=None, nick_to='??'):
if nick_from is None:
nick_from = FROM_ADDR
msg = MIMEMultipart()
msg['From'] = _format_addr('{} <{}>'.format(nick_from, FROM_ADDR))
msg['To'] = _format_addr('{} <{}>'.format(nick_to, TO_ADDRS))
msg['Subject'] = Header(subject)
msg.attach(MIMEText(content, 'html', 'utf-8'))
for attachment in attachments:
attach = MIMEText(open(attachment, 'rb').read(), 'base64', 'utf-8')
attach['Content-Type'] = 'application/octet-stream'
attach['Content-Disposition'] = 'attachment; filename="{}"'.format(
os.path.basename(attachment))
msg.attach(attach)
return msg
def notify(self, event):
try:
msg = MIMEMultipart()
msg['From'] = self.emailer_settings['from_address']
msg['To'] = self.emailer_settings['to_address']
msg['Subject'] = "{0} {1}".format(event['subject'], event['scanname'])
targets = "".join(["<li>{0}</li>".format(t) for t in event['targets']]) if event['targets'] else ""
html = str(self.emailer_settings['email_template']).format(event['server'],
event['scanname'],
event['scanid'],
event['subject'],
targets)
msg.attach(MIMEText(html, 'html'))
mail_server = smtplib.SMTP(self.emailer_settings['smtp_host'], self.emailer_settings['smtp_port'])
mail_server.sendmail(msg['From'], msg['To'], msg.as_string())
mail_server.quit()
except (Exception, AttributeError) as e: # we don't want email failure to stop us, just log that it happened
Logger.app.error("Your emailer settings in config.ini is incorrectly configured. Error: {}".format(e))
def cloudscan_notify(self, recipient, subject, git_url, ssc_url, state, scan_id, scan_name):
try:
msg = MIMEMultipart()
msg['From'] = self.from_address
msg['To'] = recipient
msg['Subject'] = subject
html = str(self.email_template).format(git_url, ssc_url, scan_name, scan_id, state, self.chatroom)
msg.attach(MIMEText(html, 'html'))
mail_server = smtplib.SMTP(self.smtp_host, self.smtp_port)
mail_server.sendmail(msg['From'], msg['To'], msg.as_string())
mail_server.quit()
except (Exception, AttributeError) as e: # we don't want email failure to stop us, just log that it happened
Logger.app.error("Your emailer settings in config.ini is incorrectly configured. Error: {}".format(e))
def test_send_mime(self, mock_smtp, mock_smtp_ssl):
mock_smtp.return_value = mock.Mock()
mock_smtp_ssl.return_value = mock.Mock()
msg = MIMEMultipart()
utils.email.send_MIME_email('from', 'to', msg, dryrun=False)
mock_smtp.assert_called_with(
configuration.get('smtp', 'SMTP_HOST'),
configuration.getint('smtp', 'SMTP_PORT'),
)
self.assertTrue(mock_smtp.return_value.starttls.called)
mock_smtp.return_value.login.assert_called_with(
configuration.get('smtp', 'SMTP_USER'),
configuration.get('smtp', 'SMTP_PASSWORD'),
)
mock_smtp.return_value.sendmail.assert_called_with('from', 'to', msg.as_string())
self.assertTrue(mock_smtp.return_value.quit.called)
def mail(self):
gonderen = "sender e-mail"
pswd = "sender e-mail passwd"
alici = "receiver e mail "
cc = "if you need add cc e-mail "
body=self.mesaj
messg = MIMEMultipart()
messg['To'] = alici
messg['Cc'] = cc
messg['From'] = gonderen
messg['Subject'] = "ANomaly tespit sistemi"
text = MIMEText(body, 'plain')
messg.attach(text)
print(self.mesaj)
try:
server = smtplib.SMTP("smtp.live.com", 587)
server.starttls()
server.login(gonderen, pswd)
server.sendmail(gonderen,[alici,cc,alici],messg.as_string())
server.close()
print("mail gönderildi")
except smtplib.SMTPException as e:
print(str(e))
def sendemail(from_addr, to_addr_list, cc_addr_list,
subject, message,
login, password,
smtpserver='smtp.gmail.com:587'):
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = from_addr
msg['To'] = ','.join(to_addr_list)
htmlmessage = '<html><head></head><body>'+message+'</body></html>'
part1 = MIMEText(message, 'plain')
part2 = MIMEText(htmlmessage, 'html')
msg.attach(part1)
msg.attach(part2)
server = smtplib.SMTP(smtpserver)
server.starttls()
server.login(login,password)
problems = server.sendmail(from_addr, to_addr_list, msg.as_string())
server.quit()
return problems
def test_mime_attachments_in_constructor(self):
eq = self.assertEqual
text1 = MIMEText('')
text2 = MIMEText('')
msg = MIMEMultipart(_subparts=(text1, text2))
eq(len(msg.get_payload()), 2)
eq(msg.get_payload(0), text1)
eq(msg.get_payload(1), text2)
# A general test of parser->model->generator idempotency. IOW, read a message
# in, parse it into a message object tree, then without touching the tree,
# regenerate the plain text. The original text and the transformed text
# should be identical. Note: that we ignore the Unix-From since that may
# contain a changed date.
def test__all__(self):
module = __import__('email')
# Can't use sorted() here due to Python 2.3 compatibility
all = module.__all__[:]
all.sort()
self.assertEqual(all, [
# Old names
'Charset', 'Encoders', 'Errors', 'Generator',
'Header', 'Iterators', 'MIMEAudio', 'MIMEBase',
'MIMEImage', 'MIMEMessage', 'MIMEMultipart',
'MIMENonMultipart', 'MIMEText', 'Message',
'Parser', 'Utils', 'base64MIME',
# new names
'base64mime', 'charset', 'encoders', 'errors', 'generator',
'header', 'iterators', 'message', 'message_from_file',
'message_from_string', 'mime', 'parser',
'quopriMIME', 'quoprimime', 'utils',
])
def test_mime_attachments_in_constructor(self):
eq = self.assertEqual
text1 = MIMEText('')
text2 = MIMEText('')
msg = MIMEMultipart(_subparts=(text1, text2))
eq(len(msg.get_payload()), 2)
eq(msg.get_payload(0), text1)
eq(msg.get_payload(1), text2)
# A general test of parser->model->generator idempotency. IOW, read a message
# in, parse it into a message object tree, then without touching the tree,
# regenerate the plain text. The original text and the transformed text
# should be identical. Note: that we ignore the Unix-From since that may
# contain a changed date.
def test__all__(self):
module = __import__('email')
# Can't use sorted() here due to Python 2.3 compatibility
all = module.__all__[:]
all.sort()
self.assertEqual(all, [
# Old names
'Charset', 'Encoders', 'Errors', 'Generator',
'Header', 'Iterators', 'MIMEAudio', 'MIMEBase',
'MIMEImage', 'MIMEMessage', 'MIMEMultipart',
'MIMENonMultipart', 'MIMEText', 'Message',
'Parser', 'Utils', 'base64MIME',
# new names
'base64mime', 'charset', 'encoders', 'errors', 'generator',
'header', 'iterators', 'message', 'message_from_file',
'message_from_string', 'mime', 'parser',
'quopriMIME', 'quoprimime', 'utils',
])
def send_email(send_from,send_to,subject,text,files=None,server="10.210.41.203"):
#assert(isinstance(send_to,list),"Send To email should be a list")
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = send_to
msg['Date'] = formatdate(localtime = True)
msg['Subject'] = subject
msg.attach(MIMEText(text,'html'))
with open(files,"rb") as f:
part = MIMEApplication(f.read(),Name=basename(files))
msg.attach(part)
smtp = smtplib.SMTP(server,0)
smtp.sendmail(send_from,send_to,msg.as_string())
smtp.quit()
def send_mail(self, subject, message, files=None):
if files is None:
files = []
msg = MIMEMultipart()
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(MIMEText(message))
# TODO files attachment max size
if files is not None:
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)
self.logger.debug('Sending mail to {0} {1}'.format(self.to_address, ' about {0}'.format(subject)))
self.server.sendmail(self.from_username, self.to_address, msg.as_string())
self.logger.debug('Mail was sent.')
def test_mime_attachments_in_constructor(self):
eq = self.assertEqual
text1 = MIMEText('')
text2 = MIMEText('')
msg = MIMEMultipart(_subparts=(text1, text2))
eq(len(msg.get_payload()), 2)
eq(msg.get_payload(0), text1)
eq(msg.get_payload(1), text2)
# A general test of parser->model->generator idempotency. IOW, read a message
# in, parse it into a message object tree, then without touching the tree,
# regenerate the plain text. The original text and the transformed text
# should be identical. Note: that we ignore the Unix-From since that may
# contain a changed date.