本文整理汇总了Python中email.MIMEImage.MIMEImage类的典型用法代码示例。如果您正苦于以下问题:Python MIMEImage类的具体用法?Python MIMEImage怎么用?Python MIMEImage使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MIMEImage类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: attach
def attach(self):
""" Attaches file(s) from cwd. Can embed html image with header. Runs on default email package. """
# ## EMBED HTML IMAGE
if self.embed:
body_text = '%s<br><img src="cid:%s"><br>%s' % (self.embedh, self.embed, self.message)
self.part = MIMEText(body_text, 'html')
self.msg.attach(self.part)
fp = open(self.embed, 'rb')
img = MIMEImage(fp.read())
fp.close()
img.add_header('Content-ID', self.embed)
self.msg.attach(img)
# ## OR DON'T ...
else:
self.part = MIMEText(self.message, "html")
self.msg.attach(self.part)
if self.files:
for f in self.files:
if f.strip().endswith('*'):
f = ambiguous_extension(f)
# print d_
self.part = MIMEBase('application', "octet-stream")
self.part.set_payload(open(f, "rb").read())
Encoders.encode_base64(self.part)
self.part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
self.msg.attach(self.part)
示例2: embed_img
def embed_img(email, img_id, img_data):
"Embeds an image in an html email"
img = MIMEImage(img_data)
img.add_header('Content-ID', '<%s>' % img_id)
img.add_header('Content-Disposition', 'inline; filename=logo.jpg')
email.attach(img)
示例3: main
def main():
msgRoot = MIMEMultipart('alternative')
msgRoot.preamble = 'This is a multi-part message in MIME format.'
with open(TEXT_FILE, 'r') as txt_f:
text = txt_f.read()
msgRoot.attach(MIMEText(text))
with open(HTML_FILE,'r') as html_f:
html = html_f.read()
if IMAGES:
msgRelated = MIMEMultipart('related')
msgRelated.attach(MIMEText(html, 'html'))
for image in IMAGES:
with open(image, 'rb') as img:
msgImage = MIMEImage(img.read())
msgImage.add_header('Content-ID', os.path.split(image)[1]) ## clean up to remove the folder location in the for cid
msgRelated.attach(msgImage)
msgRoot.attach(msgRelated)
else:
msgRoot.attach(MIMEText(html, 'html'))
if SEND:
msgRoot['To'] = SEND[0]
msgRoot['From'] = SEND[1]
msgRoot['Subject'] = SEND[2]
smtp = smtplib.SMTP('localhost')
smtp.sendmail(SEND[0], SEND[1], msgRoot.as_string())
smtp.quit()
print(msgRoot.as_string())
示例4: upload_attachments
def upload_attachments(to, gmail_user, gmail_pwd, attachment_names):
for attachment in attachment_names:
file_to_upload = 'media/%s.png' % (attachment,)
if not os.path.exists(file_to_upload):
print '!!! error: attachment %s was not generated correctly' % (attachment,)
sys.exit(1)
to = 'media+' + to
for attachment in attachment_names:
print 'uploading attachment for %s' % (attachment,)
file_to_upload = 'media/%s.png' % (attachment,)
content = MIMEMultipart()
content['From'] = gmail_user
content['To'] = to
content['Subject'] = 'attachment %s\n' % (attachment,)
img = MIMEImage(file(file_to_upload).read())
img.add_header('Content-Type', 'image/png', name=attachment + '.png')
img.add_header('Content-Disposition', 'attachment', filename=attachment + '.png')
content.attach(img)
msg = content.as_string()
smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(gmail_user, gmail_pwd)
smtpserver.sendmail(gmail_user, to, msg)
smtpserver.close()
示例5: send_mail
def send_mail(report_contents):
msg = MIMEMultipart()
msg['Subject'] = SUBJECT
msg['From'] = EMAIL_FROM
msg['To'] = ', '.join(EMAIL_TO)
fp = open('/home/pierre/es_email_intel/wordcloud.png', 'rb')
try:
msgImage = MIMEImage(fp.read())
except:
fp = open('/home/pierre/es_email_intel/1x1.png', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<wordcloud>')
msg.attach(msgImage)
part = MIMEBase('application', "octet-stream")
part.set_payload(report_contents)
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="report.html"')
msg.attach(part)
server = smtplib.SMTP(EMAIL_SERVER)
server.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
示例6: send_invoice
def send_invoice(page_type, user):
if page_type.send_email:
subject= page_type.email_subject
try:
attachment = open(page_type.attachment.url[1:],'r')
except:
attachment=None
email_to= [user.email]
plaintext = get_template('pages/custom_email.txt')
htmly = get_template('pages/custom_email.html')
try:
sponsorship = SponsorshipPackage.objects.get(title=user.companyprofile.sponsor)
except:
sponsorship = None
d = Context({'sponsorship':sponsorship, 'paypal_info': PayPalInfo.objects.all()[0], 'company':user.companyprofile})
text_content = plaintext.render(d)
html_content = htmly.render(d)
email = EmailMultiAlternatives(subject, text_content, 'Career Fair Staff', email_to)
email.attach_alternative(html_content, "text/html")
email.mixed_subtype = 'related'
f = "/opt/myenv/careerfair/static/media/uploads/static images/header.png"
fp = open(f, 'rb')
msg_img = MIMEImage(fp.read())
fp.close()
msg_img.add_header('Content-ID', '<header.png>'.format(f))
msg_img.add_header("Content-Disposition", "inline", filename="header.png")
email.attach(msg_img)
email.send()
示例7: send_mail
def send_mail(etc=""):
open_ports = get_ports()
ports = pickle.load(open("tcp_ports", "rb"))
text = """ Open Ports:<br><br>
<table cellspacing="15">
<tr>
<th>Port</th>
<th>Service</th>
</tr>
"""
for p in open_ports:
text += "<tr><td>%s</td><td>%s</td></tr>" % (p, lsofi(p))
parser = SafeConfigParser()
parser.read("./stats.conf")
msg = MIMEMultipart('related')
msg['Subject'] = "Traffic report from %s" % (socket.getfqdn())
msg['From'] = parser.get('email', 'from')
msg['To'] = parser.get('email', 'to')
msg.preamble = 'This is a multi-part message in MIME format.'
body = """
%s<br><br> <img src="cid:graph_packets"><br><br>
<img src="cid:graph_conns"><br><br>
<img src="cid:graph_bandwidth"><br><br>%s</table>""" % (etc, text)
msgBody = MIMEText(body, 'html')
msg.attach(msgBody)
attachments = [ ('packets.png', 'graph_packets'),
('conns.png', 'graph_conns'),
('bps.png', 'graph_bandwidth') ]
for attachment in attachments:
fp = open(attachment[0], 'rb')
img = MIMEImage(fp.read())
img.add_header('Content-ID', attachment[1])
fp.close()
msg.attach(img)
s = smtplib.SMTP(parser.get('email', 'smtp_server'), parser.getint('email', 'port'))
if parser.getboolean('email', 'auth'):
s.ehlo()
if parser.getboolean('email', 'use_tls'):
s.starttls()
s.ehlo()
if parser.getboolean('email', 'auth'):
s.login(parser.get('email', 'username'), parser.get('email', 'password'))
s.sendmail(parser.get('email', 'from'), [parser.get('email', 'to')], msg.as_string())
s.quit()
示例8: create_email
def create_email(from_address, to_address, subject, message, cc=None, image=None, pdf=None):
msg = MIMEMultipart('alternative')
msg['From'] = from_address
msg['To'] = to_address
msg['Subject'] = subject
if cc:
msg['Cc'] = cc
if image:
msg_img = MIMEImage(open(image, 'rb').read())
msg_img.add_header('Content-ID', '<image>')
msg_img.add_header('Content-Disposition', 'inline', filename=image)
if pdf:
msg_pdf = MIMEApplication(open(pdf, 'rb').read(), 'pdf')
msg_pdf.add_header('Content-ID', '<pdf>')
msg_pdf.add_header('Content-Disposition', 'attachment', filename=pdf)
msg_pdf.add_header('Content-Disposition', 'inline', filename=pdf)
msg.attach(MIMEText(message, 'html'))
msg.attach(msg_img)
msg.attach(msg_pdf)
return msg.as_string()
示例9: main
def main():
images = os.listdir(IMAGE_DIR)
encoded_images = {}
strFrom = ''
strTo = ''
msgRoot = MIMEMultipart('alternative')
msgRoot['Subject'] = ""
msgRoot['To'] = strTo
msgRoot['From'] = strFrom
msgRoot.preamble = 'This is a multi-part message in MIME format.'
with open('text.txt', 'r') as text:
text = text.read()
msgRoot.attach(MIMEText(text))
if not images:
msgRoot.attach(MIMEText(render_template(), 'html'))
else:
msgRelated = MIMEMultipart('related')
msgRelated.attach(MIMEText(render_template(images), 'html'))
for image in images:
with open(image, 'rb') as img:
byte_data = img.read()
msgImage = MIMEImage(byte_data)
msgImage.add_header('Content-ID', image)
msgRelated.attach(msgImage)
b64 = b64encode(byte_data)
encoded_images[image]=b64
msgRoot.attach(msgRelated)
with open("../../public_html/preview.html", 'w') as preview:
preview.write(render_template(images, preview=encoded_images))
print(msgRoot.as_string())
示例10: form_valid
def form_valid(self, form):
user = UserProfile.objects.get(user=request.user)
product = Product.objects.get(id=request.GET.get('product_id'))
try:
margin = user.margin
except:
margin = 30.0
price_increased = (product.price * margin) / 100.00
price = product.price + price_increased
to_email = [form.cleaned_data['Customer_email']]
subject = '%s - %s' % (product.model, product.manufacturer)
text_content = render_to_string('saas_app/email/product_info_email.txt')
html_content = render_to_string('saas_app/email/product_info_email.html',
{'text_content':text_content,
'price':price,
'product':product})
msg = EmailMultiAlternatives(subject,
text_content,
[user.email],
to_email)
msg.attach_alternative(html_content, 'text/html')
msg.mixed_subtype = 'related'
img_content_id = 'product'
img_data = open(product.image_url(), 'rb')
msg_img = MIMEImage(img_data.read())
img_data.close()
msg_img.add_header('Content-ID', '<{}>'.format(product.picture))
msg.attach(msg_img)
msg.send()
示例11: send_email
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"] = "[email protected]%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("[email protected]%s" % gethostname(), recipients, message.as_string())
s.quit()
return HttpResponse("OK")
except:
return HttpResponse(format_exc())
示例12: build_picture_email
def build_picture_email(self, relative_directory, num_of_results, image_store_location, files_list):
# Create the root message and fill in the from, to, and subject headers
self.msgRoot['From'] = self.gmail_sender_username
self.msgRoot['Subject'] = self.email_subject
self.msgRoot.preamble = 'This is a multi-part message in MIME format.'
# Encapsulate the plain and HTML versions of the message body in an
# 'alternative' part, so message agents can decide which they want to display.
self.msgRoot.attach(self.msgAlternative)
self.msgAlternative.attach(self.msgText)
# We reference the image in the IMG SRC attribute by the ID we give it below
self.msgAlternative.attach(self.msgPicText)
# This example assumes the image is in the current directory
for ii in range(num_of_results):
fp = open(varutil.open_subdirectory(relative_directory, image_store_location, files_list[ii]), 'rb')
msgImage = MIMEImage(fp.read())
print "Successfully added image " + files_list[ii]
fp.close()
# Define the image's ID as referenced above
msgImage.add_header('Content-ID', '<image' + str(ii) + '>')
self.msgRoot.attach(msgImage)
示例13: _create_msg
def _create_msg():
msg = MIMEMultipart("related")
msg["Subject"] = "Zabbix Screen Report: %s" % screen_name
msg["From"] = me
msg["To"] = ";".join(to_list)
msg.preamble = "This is a multi-part message in MIME format."
contents = "<h1>Screen %s</h1><br>" % screen_name
contents += "<table>"
for g_name in graphs:
with open(os.path.join(GRAPH_PATH, g_name), "rb") as fp:
msg_image = MIMEImage(fp.read())
msg_image.add_header("Content-ID", "<%s>" % g_name)
msg.attach(msg_image)
contents += ""
contents += "<tr><td><img src='cid:%s'></td></tr>" % g_name
contents += "</table>"
msg_text = MIMEText(contents, "html")
msg_alternative = MIMEMultipart("alternative")
msg_alternative.attach(msg_text)
msg.attach(msg_alternative)
return msg
示例14: invia_mail
def invia_mail(utente, template, to, subject,dominio, from_email=''):
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
from email.MIMEImage import MIMEImage
from django.conf import settings
dominio = str(dominio).replace("www.", "")
d = Context({ 'nome': utente.first_name, 'cognome': utente.last_name , 'domain': dominio, 'id': utente.id, 'confirmation_code': utente.profilo.confirmation_code })
plaintext = get_template('accounts/email/'+template+'.txt')
htmly = get_template('accounts/email/'+template+'.html')
html_content = htmly.render(d)
text_content = plaintext.render(d)
if not from_email:
from_email = settings.EMAIL_CLIENTE
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
#logo
fp = open(settings.STATIC_ROOT + "/img/logo.png", 'rb')
msg_img = MIMEImage(fp.read())
fp.close()
msg_img.add_header('Content-ID', '<{}>'.format("logo.jpg"))
msg.attach(msg_img)
return msg.send()
示例15: SendEmail
def SendEmail(subject, msgText, to, user,password, alias, imgName, replyTo=None):
sender = alias
try:
conn = SMTP('smtp.gmail.com', 587)
msg = MIMEMultipart()
msg.attach(MIMEText(msgText, 'html'))
msg['Subject']= subject
msg['From'] = sender
msg['cc'] = to
#msg['cc'] = ', '.join(to)
if replyTo:
msg['reply-to'] = replyTo
if imgName != None:
fp = open(imgName, 'rb')
img = MIMEImage(fp.read(), _subtype="pdf")
fp.close()
img.add_header('Content-Disposition', 'attachment', filename = imgName)
msg.attach(img)
conn.ehlo()
conn.starttls()
conn.set_debuglevel(False)
conn.login(user, password)
try:
conn.sendmail(sender, to, msg.as_string())
finally:
conn.close()
except:
print "Unexpected error:", sys.exc_info()[0]