def test__all__(self):
module = __import__('email')
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',
])
python类MIMEMultipart()的实例源码
def process(options, args):
config = get_config(options)
# Write the email
msg = MIMEMultipart()
msg['From'] = config['fromaddr']
msg['To'] = config['toaddrs']
msg['Subject'] = options.subject
body = options.body
msg.attach(MIMEText(body, 'plain'))
# Attach image
if options.image_file:
try:
filename = open(options.image_file, "rb")
attach_image = MIMEImage(filename.read())
attach_image.add_header('Content-Disposition',
'attachment; filename = %s'%options.image_file)
msg.attach(attach_image)
filename.close()
except:
msg.attach(MIMEText('Image attachment error', 'plain'))
# Converting email to text
text = msg.as_string()
# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.ehlo()
server.login(config['username'],config['password'])
server.sendmail(config['fromaddr'], config['toaddrs'], text)
server.quit()
def send_email(image_path,ssocr_output):
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "[TEST IMAGE] %s - %s %s" %(machine_number,hall,machine_type)
body = "My IP %s \n SSOCR output is %s \n\n\n\n\n\n\n" %(get_ip.get_ip(),ssocr_output)
msg.attach(MIMEText(body, 'plain'))
filename = "test_image.jpg"
attachment = open(image_path, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
tries = 0
while True:
if (tries > 60):
exit()
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
break
except Exception as e:
tries = tries + 1
time.sleep(1)
server.starttls()
server.login(fromaddr, "I_am_a_laundry")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
print('Send Email Successfully')
server.quit()
def send_email_direct(email_to, email_from, display_name, subject, body, attach_fname, attach_filepath, debug=False):
# find the appropiate mail server
domain = email_to.split('@')[1]
remote_server = get_mx_record(domain)
if (remote_server is None):
print "No valid email server could be found for [%s]!" % (email_to)
return
# make sure we have a display name
if (not display_name):
display_name = email_from
# connect to remote mail server and forward message on
server = smtplib.SMTP(remote_server, 25)
msg = MIMEMultipart()
msg['From'] = display_name
msg['To'] = email_to
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
if (attach_fname):
attachment = open(attach_filepath, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % attach_fname)
msg.attach(part)
smtp_sendmail_return = ""
if debug:
server.set_debuglevel(True)
try:
smtp_sendmail_return = server.sendmail(email_from, email_to, msg.as_string())
except Exception, e:
exception = 'SMTP Exception:\n' + str( e) + '\n' + str( smtp_sendmail_return)
finally:
server.quit()
def send_email_account(remote_server, remote_port, username, password, email_to, email_from, display_name, subject, body, attach_fname, attach_filepath, debug=False):
if (remote_server == "smtp.gmail.com"):
send_email_gmail(username, password, email_to, email_from, subject, body, debug)
else:
# make sure we have a display name
if (not display_name):
display_name = email_from
# connect to remote mail server and forward message on
server = smtplib.SMTP(remote_server, remote_port)
msg = MIMEMultipart()
msg['From'] = display_name
msg['To'] = email_to
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
if (attach_fname):
attachment = open(attach_filepath, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % attach_fname)
msg.attach(part)
smtp_sendmail_return = ""
if debug:
server.set_debuglevel(True)
try:
server.login(username, password)
smtp_sendmail_return = server.sendmail(email_from, email_to, msg.as_string())
except Exception, e:
exception = 'SMTP Exception:\n' + str( e) + '\n' + str( smtp_sendmail_return)
finally:
server.quit()
def sendMail(gmailUser,gmailPassword,recipient,subject,text):
msg = MIMEMultipart()
msg['From'] = gmailUser
msg['To'] = recipient
msg['Subject'] = subject
msg.attach(MIMEText(text))
mailServer = smtplib.SMTP('smtp.gmail.com', 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmailUser, gmailPassword)
mailServer.sendmail(gmailUser, recipient, msg.as_string())
mailServer.close()
print('[-] Sent email to %s :' % recipient)
def __init__(self, user, passwd, smtp,port,usettls=False):
self.mailUser = user
self.mailPassword = passwd
self.smtpServer = smtp
self.smtpPort = port
if usettls:
smtp_class = smtplib.SMTP_SSL
else:
smtp_class = smtplib.SMTP
self.mailServer = smtp_class(self.smtpServer, self.smtpPort)
self.mailServer.ehlo()
self.mailServer.login(self.mailUser, self.mailPassword)
self.msg = MIMEMultipart()
#????????mailserver
def reinitMailInfo():
self.msg = MIMEMultipart()
#????????????????????????html??plain????????????
def test_make_boundary(self):
msg = MIMEMultipart('form-data')
# Note that when the boundary gets created is an implementation
# detail and might change.
self.assertEqual(msg.items()[0][1], 'multipart/form-data')
# Trigger creation of boundary
msg.as_string()
self.assertEqual(msg.items()[0][1][:33],
'multipart/form-data; boundary="==')
# XXX: there ought to be tests of the uniqueness of the boundary, too.
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)
def test_default_multipart_constructor(self):
msg = MIMEMultipart()
self.assertTrue(msg.is_multipart())
# 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 sendEmail(SUBJECT, BODY, ATTACH_LIST, TO, FROM, SENDER,
PASSWORD, SMTP_SERVER, SMTP_PORT):
"""Sends an email."""
txt = MIMEText(BODY.encode('utf-8'), 'html', 'utf-8')
msg = MIMEMultipart()
msg.attach(txt)
_logger = logging.getLogger(__name__)
for attach in ATTACH_LIST:
try:
att = MIMEText(open(attach, 'rb').read(), 'base64', 'utf-8')
filename = os.path.basename(attach)
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="%s"' % filename
msg.attach(att)
except Exception:
_logger.error(u'?? %s ?????' % attach)
continue
msg['From'] = SENDER
msg['To'] = TO
msg['Subject'] = SUBJECT
try:
session = smtplib.SMTP()
session.connect(SMTP_SERVER, SMTP_PORT)
session.starttls()
session.login(FROM, PASSWORD)
session.sendmail(SENDER, TO, msg.as_string())
session.close()
return True
except Exception, e:
_logger.error(e)
return False
def notify(id_, email, cmd):
print('[%s] Sending report %s to %s' % (datetime.datetime.now(), id_, email))
msg = MIMEMultipart()
msg['From'] = SMTP_USER
msg['To'] = email
msg['Subject'] = "Your scan results are ready"
body = "{2}\n\nView online:\n{0}/static/results/{1}.html\n\nDownload:\n{0}/static/results/{1}.nmap\n{0}/static/results/{1}.xml\n{0}/static/results/{1}.gnmap".format(BASE_URL, id_, cmd)
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
server.ehlo()
server.starttls()
server.ehlo()
server.login(SMTP_USER, SMTP_PASS)
text = msg.as_string()
server.sendmail(SMTP_USER, email, text)
def test_make_boundary(self):
msg = MIMEMultipart('form-data')
# Note that when the boundary gets created is an implementation
# detail and might change.
self.assertEqual(msg.items()[0][1], 'multipart/form-data')
# Trigger creation of boundary
msg.as_string()
self.assertEqual(msg.items()[0][1][:33],
'multipart/form-data; boundary="==')
# XXX: there ought to be tests of the uniqueness of the boundary, too.
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)
def test_default_multipart_constructor(self):
msg = MIMEMultipart()
self.assertTrue(msg.is_multipart())
# 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_make_boundary(self):
msg = MIMEMultipart('form-data')
# Note that when the boundary gets created is an implementation
# detail and might change.
self.assertEqual(msg.items()[0][1], 'multipart/form-data')
# Trigger creation of boundary
msg.as_string()
self.assertEqual(msg.items()[0][1][:33],
'multipart/form-data; boundary="==')
# XXX: there ought to be tests of the uniqueness of the boundary, too.