def _build_multipart_msg(message, images): """Build Multipart message with in-line images.""" _LOGGER.debug('Building multipart email with embedded attachment(s)') msg = MIMEMultipart('related') msg_alt = MIMEMultipart('alternative') msg.attach(msg_alt) body_txt = MIMEText(message) msg_alt.attach(body_txt) body_text = ['<p>{}</p><br>'.format(message)] for atch_num, atch_name in enumerate(images): cid = 'image{}'.format(atch_num) body_text.append('<img src="cid:{}"><br>'.format(cid)) try: with open(atch_name, 'rb') as attachment_file: attachment = MIMEImage(attachment_file.read()) msg.attach(attachment) attachment.add_header('Content-ID', '<{}>'.format(cid)) except FileNotFoundError: _LOGGER.warning('Attachment %s not found. Skipping', atch_name) body_html = MIMEText(''.join(body_text), 'html') msg_alt.attach(body_html) return msg
def setUp(self): #set up the image for the message ePic = 'v:/workspace/HandlingEmail_Homework/src/python-logo.png' att = open(ePic, 'rb') img = MIMEImage(att.read()) att.close() img.add_header('Content-Disposition', 'attachment', filename=os.path.basename(ePic)) #set up the message body msgText = MIMEText("This is a test string", 'plain') #build the message msg = MIMEMultipart() msg['To'] = '*****@*****.**' msg['From'] = '*****@*****.**' msg['Subject'] = 'Test Email' msg.attach(msgText) msg.attach(img) self.Mmsg = msg #create a set for comparison self.attachmentSet = {msgText.as_string(), img.as_string()} #engages the function attachments = [ePic] mailObj = emailReturn('*****@*****.**', 'This is a test string', attachments) self.mailTest = mailObj
def send_image_email(path, title = u'Image Report', user = "******", pwd = p, to = ''): if to is '': to = user img = dict(title=title, path=path, cid=str(uuid.uuid4())) msg = MIMEMultipart('related') msg['Subject'] = Header(u'Report…', 'utf-8') msg['From'] = user msg['To'] = to msg_alternative = MIMEMultipart('alternative') msg.attach(msg_alternative) msg_text = MIMEText(u'[image: {title}]'.format(**img), 'plain', 'utf-8') msg_alternative.attach(msg_text) msg_html = MIMEText(u'<div dir="ltr">' '<img src="cid:{cid}" alt="{alt}"><br></div>' .format(alt=cgi.escape(img['title'], quote=True), **img), 'html', 'utf-8') msg_alternative.attach(msg_html) with open(img['path'], 'rb') as file: msg_image = MIMEImage(file.read(), name=os.path.basename(img['path'])) msg.attach(msg_image) msg_image.add_header('Content-ID', '<{}>'.format(img['cid'])) s = smtplib.SMTP(host='smtp.gmail.com',port=587) s.ehlo() s.starttls() s.ehlo() s.login(user,pwd) s.sendmail(user,to,msg.as_string()) s.quit()
def set_msg(self): msg = MIMEMultipart() msg["From"] = Mailer._format_addr((self.name + "<%s>" % self.email)) msg["Subject"] = Header(self.sbj, "utf-8").encode() if self.mail_text: msg.attach(MIMEText(self.mail_text, "html", "utf-8")) else: raise Exception("| ERROR: Check your mail template") # Attach Logo with open(files["logo"], "rb") as l: logo = MIMEImage(l.read()) logo.add_header("Content-ID", "<Logo>") logo.add_header("X-Attachment-Id", "Logo") msg.attach(logo) # Attach Pdf try: with open(files["attachment"], "rb") as ip: intro = MIMEApplication(ip.read()) intro.add_header("Content-Disposition", "attachment", filename=files["attachment_name"]) msg.attach(intro) except Exception as e: print("| ERROR: Wrong Attachment") print(e) return msg
def send_mail(self, correlations, time, script): """Simple convenience function which sends an email \ from the configured sender to receivers. :param correlations: number representing the combined \ number of threats to be reported. :type correlations: :mod:`int` :param time: the time it took for the calling program \ to execute and finish successfully. :type time: :mod:`string` :param script: the script which was invoked such that a \ detailed job description can be provided to correlation notifications. :type time: :mod:`string` """ description = self.get_description(script) message = Template(""" <br><img src="cid:image1" width="200"><br> <p>You are receiving this email because you are subscribed to <b>Assurant's Threat Intelligence notification service</b>.</p> <p><b>$corr threat correlation(s) have been identified</b> whilst running one of our threat correlation scripts.</p> <p>Identified correlations relate to: <b>$desc</b>.</p> <p>To view correlation(s) please visit the Kibana dashboard.</p> <p>Time taken to identify correlations was <b>$dur seconds</b>.</p> <p><i>To unsubscribe from this service please contact $sender</i>.</p> """) fullMessage = message.substitute(corr=correlations, dur=time, sender=sender, desc=description) # Create the root message and fill in the from, to, and subject headers msgRoot = MIMEMultipart('related') msgRoot['Subject'] = 'Assurant Threatelligence Update' msgRoot['From'] = sender msgRoot['To'] = receivers 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. msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText('This is the alternative plain text message.') msgAlternative.attach(msgText) # We reference the image in the IMG SRC attribute by the ID we give it below #msgRoot = MIMEText() msgText = MIMEText(fullMessage, 'html') msgAlternative.attach(msgText) # This example assumes the image is in the current directory fp = open('assurant-logo.png', 'rb') msgImage = MIMEImage(fp.read()) fp.close() # Define the image's ID as referenced above msgImage.add_header('Content-ID', '<image1>') msgRoot.attach(msgImage) smtpObj = smtplib.SMTP('smtp.gmail.com', 587) smtpObj.ehlo() smtpObj.starttls() smtpObj.login(sender, '') smtpObj.sendmail(sender, receivers, msgRoot.as_string()) smtpObj.quit()
def email_project(request, slug): project = get_object_or_404(Project, slug=slug) funding_program = FundingProgram.objects.get(id=project.funding_program_id) lpms = AssignedEmployee.objects.filter(project_id=project.id, role='Project manager').values('employee_id') project_managers = Employee.objects.filter(id__in=lpms).order_by('name', 'first_surname', 'second_surname') lprs = AssignedEmployee.objects.filter(project_id=project.id, role='Principal researcher').values('employee_id') principal_researchers = Employee.objects.filter(id__in=lprs).order_by('name', 'first_surname', 'second_surname') project_leader = Organization.objects.get(id=project.project_leader_id) consortium_members = [] for consortium_member in ConsortiumMember.objects.all().filter(project_id=project.id): org = Organization.objects.get(id=consortium_member.organization.id) consortium_members.append(org.name) html_content = render_to_string('projects/project_email_template.html', { 'project': project, 'funding_program': funding_program, 'project_managers': project_managers, 'principal_researchers': principal_researchers, 'project_leader': project_leader, 'consortium_members': consortium_members, }) text_content = strip_tags(html_content) msg = EmailMultiAlternatives( '[NEW PROJECT]: ' + project.title, # subject text_content, # message settings.PROJECTS_SENDER_EMAIL, # from settings.PROJECTS_RECEPTOR_EMAILS, # to ) try: image_file = open(project.logo.path, 'rb') msg_image = MIMEImage(image_file.read()) image_file.close() msg_image.add_header('Content-ID', '<image>', filename=project.logo.path) msg.attach(msg_image) except: pass try: image_file = open(funding_program.logo.path, 'rb') msg_image = MIMEImage(image_file.read()) image_file.close() msg_image.add_header('Content-ID', '<image>', filename = funding_program.logo.path) msg.attach(msg_image) except: pass msg.attach_alternative(html_content, "text/html") msg.send() return HttpResponseRedirect(reverse('project_index'))
def sendMail(): sender = '*****@*****.**' receiver = ['*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**'] # receiver = ['*****@*****.**'] smtpserver = 'mail.epcare.com.cn' username = '******' password = '******' yestoday = date.today() - timedelta(hours=24); msgRoot = MIMEMultipart('related') msgRoot['Subject'] = '每日域报告' msgRoot['From'] = sender msgRoot['To'] = ';'.join(receiver) msgRoot["Date"] = Utils.formatdate(localtime = 1) #文本内容 html = ''' <html> <head><head> <body> <p>Hi, all<br> <br> 以上是昨天各个域的发送情况,详看附件!<br> <br> 顺祝工作愉快!<br> <br> <img src="cid:image1"> </p> </body> </html> ''' msgText = MIMEText(html, 'html', 'utf-8') msgRoot.attach(msgText) fp = open('D:\\me.jpg', 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<image1>') msgRoot.attach(msgImage) #构造附件 the_dir = 'C:\\Users\\zhang\\Desktop\\%s\\' % yestoday if os.path.exists(the_dir) : os.chdir('%s' % (the_dir)) else: print 'no %s' % the_dir sys.exit() for dirfile in os.listdir(the_dir): if os.path.isfile(dirfile): csvfile = open(dirfile, 'rb') att = MIMEText(csvfile.read(), 'base64', 'utf-8') csvfile.close() att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename="%s"' % dirfile msgRoot.attach(att) smtp = smtplib.SMTP() smtp.connect(smtpserver) smtp.login(username, password) smtp.sendmail(sender, receiver, msgRoot.as_string()) smtp.quit()
def emailTumblr(gmail_user_name, gmail_pass_word, random_word ): # now send the email to Tumblr # email set up server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() #Next, log in to the server #print "user: "******"pass: "******"rb").read(), _subtype="jpeg") img.add_header('Content-Disposition', 'attachment; filename="newImageChanged.jpg"') msg.attach(img) server.sendmail(me, tumblr_email, msg.as_string()) server.quit()
def mysendmail(mailist,subject,msg,filename=None): USERNAME,PASSWD,SMTP = mailconfig() MAIL_LIST = re.split(',|;',mailist) try: message = MIMEMultipart() message.attach(MIMEText(msg)) message["Subject"] = subject message["From"] = USERNAME message["To"] = ";".join(MAIL_LIST) if filename != None and os.path.exists(filename): ctype,encoding = mimetypes.guess_type(filename) if ctype is None or encoding is not None: ctype = "application/octet-stream" maintype,subtype = ctype.split("/",1) attachment = MIMEImage((lambda f: (f.read(), f.close()))(open(filename, "rb"))[0], _subtype = subtype) attachment.add_header("Content-Disposition", "attachment", filename = os.path.split(filename)[1]) message.attach(attachment) s = smtplib.SMTP() s.connect(SMTP) s.login(USERNAME,PASSWD) s.sendmail(USERNAME,MAIL_LIST,message.as_string()) s.quit() return True except Exception,errmsg: print "Send mail failed to : %s" % errmsg return False
def send_email(sender, recipient): """ Send email message """ msg = MIMEMultipart() msg['Subject'] = 'Python Email Test' msg['To'] = recipient msg['From'] = sender subject = 'Python email Test' message = 'Images attached.' # attach image files files = os.listdir(os.getcwd()) gifsearch = re.compile(".gif", re.IGNORECASE) files = filter(gifsearch.search, files) for filename in files: path = os.path.join(os.getcwd(), filename) if not os.path.isfile(path): continue img = MIMEImage(open(path, 'rb').read(), _subtype="gif") img.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(img) part = MIMEText('text', "plain") part.set_payload(message) msg.attach(part) # create smtp session session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) session.ehlo() session.starttls() session.ehlo password = getpass.getpass(prompt="Enter you google's password: "******"Email sent." session.quit()
def emailReturn(eAddress, eBody, eAttach): msg = MIMEMultipart() msg['To'] = eAddress msgBody = MIMEText(eBody) msg.attach(msgBody) for attachment in eAttach: #test if it is an mimeMainType = mimetypes.guess_type(attachment)[0].split('/')[0] mimeSubType = mimetypes.guess_type(attachment)[0].split('/')[1] if mimeMainType == 'image': imgAttachment = open(attachment, 'rb') img = MIMEImage(imgAttachment.read()) imgAttachment.close() img.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachment)) msg.attach(img) elif mimeMainType == 'text': if mimeSubType == 'plain': plainText = MIMEText(attachment, 'plain') msg.attach(plainText) if mimeSubType == 'html': htmlText = MIMEText(attachment, 'html') msg.attach(htmlText) return msg
def send_email_with_file(addressee, text, subject, file_list): """发送file email""" msg = MIMEMultipart() msg.attach(MIMEText(text, _charset='utf-8')) msg['Subject'] = Header(subject, 'utf-8') msg['From'] = '*****@*****.**' msg['To'] = addressee for file_name in file_list: ctype, encoding = mimetypes.guess_type(file_name) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) attachment = MIMEImage((lambda f: (f.read(), f.close())) \ (open(file_name, 'rb'))[0], _subtype =subtype) attachment.add_header('Content-Disposition', 'attachment', filename=file_name) msg.attach(attachment) try: smtp = smtplib.SMTP() smtp.connect('smtp.ym.163.com', 25) smtp.login(msg['From'], 'zhoujb.19890211') smtp.sendmail(msg['From'], addressee, msg.as_string()) except Exception,e: logger.exception('send_email: %s' % (str(e)))
def create_message(request, subject, html, from_email, mailify=True): message = MIMEMultipart('alternative') message['From'] = from_email message['Subject'] = subject if mailify: mailify_html(request, html, message) else: body_html = u'<html><body>%s</body></html>' % html bodyplain = html2text.html2text(body_html) message.attach(MIMEText(bodyplain.encode('UTF-8'), 'plain', 'UTF-8')) message.attach(MIMEText(body_html.encode('UTF-8'), 'html', 'UTF-8')) for k in request.params.keys(): if k.startswith("attachment"): tmpattachment = request.params[k] if tmpattachment.filename: if tmpattachment.filename.endswith(('.png', '.tiff', '.gif', '.bmp', 'jpeg', '.tif', '.jpg')): attachment = MIMEImage(tmpattachment.value) elif tmpattachment.filename.endswith(('.pdf', '.zip')): attachment = MIMEApplication(tmpattachment.value) else: attachment = MIMEText(tmpattachment.value) attachment.add_header('Content-Disposition', 'attachment', filename=tmpattachment.filename) message.attach(attachment) return message
def get_attachments(self): attachments = super().get_attachments() filename = finders.find('images/logo.png') f = open(filename, 'rb') opin_logo = MIMEImage(f.read()) opin_logo.add_header('Content-ID', '<{}>'.format('opin_logo')) return attachments + [opin_logo]
def send_email(): mail_username = EMAIL_USER_NAME mail_password = EMAIL_PASSWORD from_addr = FROM_ADDRESS to_addrs = TO_ADDRESS #html_content send_html = get_html() # HOST & PORT HOST = EMAIL_HOST PORT = HOST_PORT # Create SMTP Object smtp = smtplib.SMTP() smtp.connect(HOST,PORT) smtp.login(mail_username,mail_password) msgRoot = MIMEMultipart('related') msg1 = MIMEText(send_html,'html','utf-8') with open(IMAGE_PATH,'rb') as f: msg2 = MIMEImage(f.read()) msg2['Content-Disposition'] = 'inline;filename="image.jpg"' msg2.add_header('Content-ID', '<image1>') with open(TABLE_SAVE_PATH,'rb') as f: msg3 = MIMEText(f.read(),'base64','gb2312') msg3["Content-Type"] = 'application' msg3["Content-Disposition"] = 'attachment;filename="爬虫库资源详情.xlsx"' msgRoot.attach(msg1) msgRoot.attach(msg2) msgRoot.attach(msg3) msgRoot['From'] = from_addr msgRoot['To'] = ';'.join(to_addrs) msgRoot['Subject']= Header('爬虫库状态通知邮件(' + str(date.today()) + ')','utf-8') smtp.sendmail(from_addr,to_addrs,msgRoot.as_string()) smtp.quit()
def addimg(src,imgid): fp = open(src,'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID',imgid) return msgImage
def sendmail(sender, receivers, mail): message = MIMEMultipart() message['From'] = formataddr((Header(sender['nickname'], 'utf-8').encode(), sender['address'])) message['To'] = ','.join(map(lambda x: formataddr((Header(x[0], 'utf-8').encode(), x[1])), receivers)) message['Subject'] = Header(mail['subject'], 'utf-8').encode() if 'content' in mail: message.attach(MIMEText(mail['content'], 'plain', 'utf-8')) if 'content_html' in mail: message.attach(MIMEText(mail['content_html'], 'html', 'utf-8')) if 'attachments' in mail: for attachment in mail['attachments']: att = MIMEText(attachment[1], 'base64', 'utf-8') att["Content-Type"] = "application/octet-stream" att["Content-Disposition"] = 'attachment; filename="{}"'.format(attachment[0]) message.attach(att) if 'images' in mail: for image in mail['images']: img = MIMEImage(image['data']) img.add_header('Content-ID', '<{}>'.format(image['Content-ID'])) message.attach(img) server = smtplib.SMTP_SSL(sender['smtp_server'], sender['smtp_port']) server.login(sender['address'], sender['password']) server.sendmail(sender['address'], list(zip(*receivers))[1], message.as_string()) server.quit()
def send_mail(self): # need to ensure address is minimally valid email sent_emails = ['', None] with open(os.path.join( BASE_DIR, 'registration/static/registration/email_text/genericbanner.png' ), 'rb') as fp: image1 = MIMEImage(fp.read()) image1.add_header('Content-ID', '<{}>'.format('image1')) for key in self._recipients: reg_id = key address = self._recipients[key]['email'] salutation = self._recipients[key]['salutation'] email_body = self._message if address not in sent_emails: if salutation not in ('', None): email_body = 'Dear ' + salutation + ':<br/><br/>' + \ self._message if self._msg_type in ('docs', 'thanks'): email_body = self._insert_passwords(email_body, key) email_body = '<img src="cid:image1" style="width:auto; max-width:90%;"/><br/><br/>' + email_body email_body = '<html><body>' + email_body + '</body></html>' email = EmailMessage( subject = self._subject, body = email_body, to = [address] ) email.content_subtype = 'html' email.mixed_subtype = 'related' email.attach(image1) email.send() sent_emails.append(address) time.sleep(SLEEP_TIME)
def create_and_send_mail_messages(messages): if not settings.EMAIL_HOST: return sender = Header(unicode(settings.APP_SHORT_NAME), 'utf-8') sender.append('<%s>' % unicode(settings.DEFAULT_FROM_EMAIL)) sender = u'%s <%s>' % (unicode(settings.APP_SHORT_NAME), unicode(settings.DEFAULT_FROM_EMAIL)) try: connection = SMTP(str(settings.EMAIL_HOST), str(settings.EMAIL_PORT)) """ connection = SMTP(str(settings.EMAIL_HOST), str(settings.EMAIL_PORT), local_hostname=DNS_NAME.get_fqdn()) """ if (bool(settings.EMAIL_USE_TLS)): connection.ehlo() connection.starttls() connection.ehlo() if settings.EMAIL_HOST_USER and settings.EMAIL_HOST_PASSWORD: connection.login(str(settings.EMAIL_HOST_USER), str(settings.EMAIL_HOST_PASSWORD)) if sender is None: sender = str(settings.DEFAULT_FROM_EMAIL) for recipient, subject, html, text, media in messages: msgRoot = MIMEMultipart('related') msgRoot['Subject'] = Header(subject, 'utf-8') msgRoot['From'] = sender to = Header(recipient.username, 'utf-8') to.append('<%s>' % recipient.email) msgRoot['To'] = to #msgRoot.preamble = 'This is a multi-part message from %s.' % unicode(settings.APP_SHORT_NAME).encode('utf8') msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgAlternative.attach(MIMEText(text.encode('utf-8'), _charset='utf-8')) msgAlternative.attach(MIMEText(html.encode('utf-8'), 'html', _charset='utf-8')) for alias, location in media.items(): fp = open(location, 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<'+alias+'>') msgRoot.attach(msgImage) try: connection.sendmail(sender, [recipient.email], msgRoot.as_string()) except Exception, e: logging.error("Couldn't send mail using the sendmail method: %s" % e) try: connection.quit() except socket.sslerror: connection.close()
def generate_message(folder, mail_subject, mail_from, mail_to): message = MIMEMultipart() message['Subject'] = mail_subject message['From'] = mail_from message['To'] = mail_to related = MIMEMultipart('related') message.attach(related) content = open(os.path.join(folder, "generated.html")).read() images = [] print(os.listdir(folder)) for file in os.listdir(folder): _, extension = os.path.splitext(file) print(file, _, extension, mimetypes.types_map.get(extension, "unknown").startswith("image/")) if mimetypes.types_map.get(extension, "unknown").startswith("image/"): with open(os.path.join(folder, file), 'rb') as fp: img = MIMEImage(fp.read(), name=file) img.add_header('Content-ID', "<" + file + "@mailer>") img.add_header('Content-Disposition', 'inline', filename=file) content = content.replace(file, "cid:" + file + "@mailer") images.append(img) related.attach(MIMEText(content, 'html', "utf-8")) for image in images: related.attach(image) return message
def main(): msg = MIMEMultipart() msg['Subject'] = 'Python (-++-) Test' msg['To'] = recipient msg['From'] = sender files = os.listdir(directory) pngsearch = re.compile(".png", re.IGNORECASE) files = filter(pngsearch.search, files) for filename in files: path = os.path.join(directory, filename) if not os.path.isfile(path): continue img = MIMEImage(open(path, 'rb').read(), _subtype="png") img.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(img) part = MIMEText('text', "plain") part.set_payload(message) msg.attach(part) session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) session.ehlo() session.starttls() session.ehlo session.login(sender, password) session.sendmail(sender, recipient, msg.as_string()) session.quit()
def inflate(config, template, datas): sender = config['sender'] subject = template['subject'] body_template = Template(template['body']) attachments = [] for cid in template['attachment'].keys(): info = template['attachment'][cid] with open(info['path'], 'rb') as f: image = MIMEImage(f.read()) image.add_header('Content-ID', '<{0}>'.format(cid)) attachments.append(image) for data in datas: receiver = data['email'] root = MIMEMultipart('related') root['Subject'] = subject root['From'] = sender root['To'] = receiver try: body = body_template.render(**data) except: raise Exception("Check template's variables and csv header") text = MIMEText(body, 'html', 'utf-8') root.attach(text) for attach in attachments: root.attach(attach) yield dict( sender = sender, receiver = receiver, message = root)
def avatar_updated_handler(sender, instance, **kwargs): try: original_mentor = Mentor.objects.get(id=instance.id) except ObjectDoesNotExist: return if not instance.avatar: return if original_mentor.avatar != instance.avatar: instance.avatar_approved = False img = MIMEImage(instance.avatar.read()) img.add_header('Content-Id', 'avatar') img.add_header("Content-Disposition", "inline", filename="avatar") email( subject=f"{instance.user.first_name} {instance.user.last_name} | Mentor Avatar Changed", template_name='avatar-changed-mentor', merge_global_data={ 'first_name': instance.user.first_name, 'last_name': instance.user.last_name, 'image': 'avatar', 'approve_url': f"{settings.SITE_URL}{instance.get_approve_avatar_url()}", 'reject_url': f"{settings.SITE_URL}{instance.get_reject_avatar_url()}", }, recipients=[settings.CONTACT_EMAIL], preheader='Mentor Avatar Changed', attachments=[img], mixed_subtype='related', )
def sendmail(self,receiver,title,body): logfile = open('/usr/lib/zabbix/alertscripts/logs/alarm_mail.log','a') host = 'smtp.test.com' port = 25 sender = '*****@*****.**' pwd = 'passwd' msg = MIMEMultipart('related') msg['subject'] = title msg['from'] = sender msg['To'] = ','.join(receiver) con_txt = MIMEText(body, 'html','utf-8') msg.attach(con_txt) img_path = '/usr/lib/zabbix/alertscripts/imgs/%s.png' %self.GetItemID(body) if os.path.exists(img_path): a = open(img_path,'r') img = a.read() a.close() else: a = open('/usr/lib/zabbix/alertscripts/imgs/404.jpg','r') img = a.read() a.close() con_img = MIMEImage(img) con_img.add_header('Content-ID','<img1>') msg.attach(con_img) try: s = smtplib.SMTP(host, port) s.login(sender, pwd) s.sendmail(sender, receiver, msg.as_string()) print 'The mail named %s to %s is sended successly.' % (title, receiver) log = '%s, OK,%s,%s\n' %(time.ctime(),title,receiver) except Exception,e: print "失败:"+str(e) log = '%s, Fail,%s,%s,%s\n' %(time.ctime(),title,receiver,str(e))
def __send(to_list, sub, content, filenames = None): try: message = MIMEMultipart() message.attach(MIMEText(content, _subtype = 'html', _charset = 'UTF-8')) message["Subject"] = sub message["From"] = EmailUtil.me message["To"] = ";".join(to_list) if filenames is not None : for filename in filenames : if os.path.exists(filename): ctype, encoding = mimetypes.guess_type(filename) if ctype is None or encoding is not None: ctype = "application/octet-stream" subtype = ctype.split("/", 1) attachment = MIMEImage((lambda f: (f.read(), f.close()))(open(filename, "rb"))[0], _subtype = subtype) attachment.add_header("Content-Disposition", "attachment", filename = re.findall('\/(\w+\.\w+)$', filename)[0]) message.attach(attachment) server = smtplib.SMTP() server.connect(EmailUtil.mail_host) server.login(EmailUtil.mail_user, EmailUtil.mail_pass) server.sendmail(EmailUtil.me, to_list, message.as_string()) server.close() return True except Exception, e: print 'EmailUtil.__send error:', str(e)
def send(self, subject, html, smtp_server, images=[], zipfile=None): msg = MIMEMultipart() msg['From'] = '{0} <{1}>'.format(self.name, self.sender) msg['To'] = COMMASPACE.join(self.to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject if self.reply_to is not None: msg['Reply-To'] = self.reply_to msg.attach(MIMEText(html.encode('utf-8'), 'html', 'utf-8')) for i, image in enumerate(images): img = MIMEImage(image.read()) img.add_header('Content-ID', '<image{0}>'.format(i+1)) msg.attach(img) if zipfile: zip = MIMEBase('application', 'zip') zip.set_payload(zipfile.read()) encoders.encode_base64(zip) zip.add_header('Content-Disposition', 'attachment; filename=%s' % basename(zipfile)) msg.attach(zip) smtp = smtplib.SMTP(smtp_server) smtp.sendmail(self.sender, set(self.to+self.bcc), msg.as_string()) smtp.close()
def new_message(address, body, args): # create new message msg = MIMEMultipart() msg["To"] = address p = MIMEText(body, "plain") msg.attach(p) if len(args) > 0: for a in args: # open the file f = open(a, "rb") # try to guess type and build appropriate object t = mimetypes.guess_type(a) if t[0].find("image") > -1: x = MIMEImage(f.read()) elif t[0].find("application") > -1: x = MIMEApplication(f.read()) f.close() # add header info x.add_header("Content-Disposition", "attachment", filename=os.path.basename(a)) # attach to the message msg.attach(x) # return the message #print(msg.as_string()) return msg
def send_mail_with_pic(to_list,subject,pic=None): msg = MIMEMultipart() msg['To'] = ';'.join(to_list) msg['From'] = '*****@*****.**' msg['Subject'] = '%s' % subject txt = MIMEText("发送给你一些图片,瞧瞧吧,亲~~",'plain','utf8') msg.attach(txt) if pic == None: pic = "" else: for i in pic: if os.path.exists(i) != True: continue else: file1 = "%s" % i image = MIMEImage(open(file1,'rb').read()) image.add_header('Content-ID','<image1>') msg.attach(image) server = smtplib.SMTP() server.connect(mail_host) server.starttls() server.login(mail_user,mail_pass) server.sendmail(msg['From'],msg['To'],msg.as_string()) server.quit()
def sendGmailwithpng(usr, pwd,recipients,subject,body,file): server = 'smtp.gmail.com' port = 587 msg = MIMEMultipart() msg['Subject'] = subject msg['To'] = ",".join(recipients[0:]) msg['From'] = usr path,filename = os.path.split(file) img = MIMEImage(open(file, 'rb').read(), _subtype="png") img.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(img) part = MIMEText('text', "plain") part.set_payload(body) msg.attach(part) session = smtplib.SMTP(server, port) #~ session.set_debuglevel(True) session.ehlo() session.starttls() session.ehlo() session.login(usr,pwd) session.sendmail(usr, recipients,msg.as_string()) session.quit()
def attachImage(self, content_id=None, jpeg=True, content_type=None, inline=False, force_filename=False, extension=None): if jpeg: real_filename = self.JPG_FILENAME file_suffix = 'jpg' if not extension else extension else: real_filename = self.PNG_FILENAME file_suffix = 'png' if not extension else extension with tempfile.NamedTemporaryFile(prefix="email2pdf_unittest_image", suffix="." + file_suffix) as temp_file: _, basic_file_name = os.path.split(temp_file.name) with open(real_filename, 'rb') as image_file: image = MIMEImage(image_file.read()) if content_id: image.add_header('Content-ID', content_id) if content_type: self._replace_header(image, 'Content-Type', content_type) if inline: if force_filename: self._replace_header(image, 'Content-Disposition', 'inline; filename="%s"' % basic_file_name) else: self._replace_header(image, 'Content-Disposition', 'inline') else: self._replace_header(image, 'Content-Disposition', 'attachment; filename="%s"' % basic_file_name) self.msg.attach(image) if inline and not force_filename: return None else: return basic_file_name
Test-Cases execution chart:</b></font> <br/><br/> <img src="cid:image1" align="left" width="300" height="205" ><img src="cid:image2" align="left" width="300" height="205" > </br></br>''' html = html1 + html3 + html2 html = html + "</body></html>" # Record the MIME types. msgHtml = MIMEText(html, 'html') img = open('scenarioCRM.png', 'rb').read() msgImg = MIMEImage(img, 'png') msgImg.add_header('Content-ID', '<image1>') msgImg.add_header('Content-Disposition', 'inline', filename='scenarioCRM.png') img = open('testCRM.png', 'rb').read() msgImg1 = MIMEImage(img, 'png') msgImg1.add_header('Content-ID', '<image2>') msgImg1.add_header('Content-Disposition', 'inline', filename='testCRM.png') strFrom = "*****@*****.**" strTo = "*****@*****.**" strTo1 = "*****@*****.**" sub = "Automation Report:" # Create message container. msgRoot = MIMEMultipart('related') msgRoot['Subject'] = sub
def send(self, recipients, subject="", body="", filename=None): msg = MIMEMultipart() if not self._username or not self._userpass: raise UserInfoError() if isinstance(recipients, str): recipients = [recipients] msg['From'] = self._username msg['To'] = self.COMMASPACE.join(recipients) if subject == "": msg['Subject'] = self._subject else: msg['Subject'] = subject if body == "": body = self._body else: body = MIMEText(body) msg.attach(body) if filename is not None: import os import mimetypes file_basename = os.path.basename(filename) ctype, encoding = mimetypes.guess_type(filename) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/') if maintype == 'image': from email.mime.image import MIMEImage with open(filename, 'rb') as fp: part = MIMEImage(fp.read(), _subtype=subtype) else: from email.mime.base import MIMEBase from email import encoders with open(filename, 'rb') as fp: part = MIMEBase(maintype, subtype) part.set_payload(fp.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment', filename=file_basename) msg.attach(part) try: self._initialize() self._sendmail(recipients, msg) except smtplib.SMTPAuthenticationError as e: print(str(e)) except smtplib.SMTPConnectError as e: print(str(e)) except smtplib.SMTPServerDisconnected as e: print(str(e)) self._server = None self._initialize() self._sendmail(recipients, msg) except smtplib.SMTPException as e: print(str(e)) else: print("Sent mail from %s to %s, Success!!" % (self._username, recipients))
def new_event_notification(notifications=None, scenario=False): """ Build and send HTML email for a new event or scenario Args: event (ShakeMap): which ShakeMap the Notification is attached to group (Group): The Group that this Notification is being send to notification (Notification): The Notification that will be sent scenario (bool): True if the user is running a scenario Returns: None """ events = [n.event for n in notifications] group = notifications[0].group notification = notifications[0] # aggregate multiple events for n in notifications[1:]: n.status = 'aggregated' # create HTML for the event email not_builder = NotificationBuilder() message = not_builder.build_new_event_html(events=events, notification=notification, name=group.template) notification.status = 'Message built' #initiate message msg = MIMEMultipart() # attach html message_type = 'html' if '<html>' in message else 'plain' encoded_message = MIMEText(message.encode('utf-8'), message_type, 'utf-8') msg.attach(encoded_message) # get and attach map for count, event in enumerate(events): map_image = open(os.path.join(event.directory_name, 'image.png'), 'rb') msg_gmap = MIMEImage(map_image.read(), _subtype='png') map_image.close() msg_gmap.add_header( 'Content-ID', '<gmap{0}_{1}>'.format(count, notification.shakecast_id)) msg_gmap.add_header('Content-Disposition', 'inline') msg.attach(msg_gmap) # find the ShakeCast logo temp_manager = TemplateManager() configs = temp_manager.get_configs('new_event', name=notification.group.template) logo_str = os.path.join(sc_dir(), 'view', 'assets', configs['logo']) # open logo and attach it to the message logo_file = open(logo_str, 'rb') msg_image = MIMEImage(logo_file.read(), _subtype='png') logo_file.close() msg_image.add_header('Content-ID', '<sc_logo_{0}>'.format(notification.shakecast_id)) msg_image.add_header('Content-Disposition', 'inline') msg.attach(msg_image) mailer = Mailer() me = mailer.me # get notification format not_format = group.get_notification_format(notification, scenario) # get notification destination based on notification format you = [ user.__dict__[not_format] for user in group.users if user.__dict__.get(not_format, False) ] if len(you) > 0: if len(events) == 1: subject = event.title.encode('utf-8') else: mags = [] for e in events: if e.event_id == 'heartbeat': mags += ['None'] else: mags += [e.magnitude] subject = '{0} New Events -- Magnitudes: {1}'.format( len(events), str(mags).replace("'", '')) if scenario is True: subject = 'SCENARIO: ' + subject msg['Subject'] = subject msg['To'] = ', '.join(you) msg['From'] = me mailer.send(msg=msg, you=you) notification.status = 'sent' notification.sent_timestamp = time.time() else: notification.status = 'not sent - no users'
def main(): if request.method == "POST": nombre=request.form["nombre"] acompanante=request.form["acompanante"] ninos=request.form["ninos"] consulta=request.form["consulta"] email=request.form["email"] bus=request.form["bus"] print('Confirmada asistencia para Nombre: {}, acompanante: {}, ninos: {}, email: {}, bus : {}'.format(nombre, acompanante, ninos, email, bus)) try: # Send mail to = config.to gmail_user = config.gmail_user gmail_pwd = config.gmail_pwd smtpserver = smtplib.SMTP("smtp.gmail.com",587) smtpserver.ehlo() smtpserver.starttls() smtpserver.login(gmail_user, gmail_pwd) header = 'To:' + ", ".join(to) + '\n' + 'From: ' + gmail_user + '\n' if email is not None: header=header+'CC: {}\n'.format(email) header=header+'Subject:[BODA CLAUNOEL - Invitacion Confirmada] {}\n'.format(nombre) msg = """ _ _ /' `\ /' /' `\ /' ' ) ) /' /' ) /' /' ._) /' // /' /' /' (___,/'____ _____,/' ____ /' /' ____ /'/ /' ____ ____ /' /' ) /' )--/' /' /' ) /' /' /' ) /' / /' / /' /' )--/' ) /' /' /'/' /' /' /' /' /' /' /' /' /' /' /' /' //' /' /' /(___,/' /' (,/' (___,/' (___,/' (___,/(__(___,/(__ (_____,/'(__(___,/(__(___,/(__(,/' (_,(___,/' (________(__ OLE OLE Y OLE! Nueva Confirmacion realizada ------------------------------------------------------- Nombre : {} Acompanante : {} Ninos : {} Bus : {} Consulta : {} email : {} ------------------------------------------------------- ---@@@@@@@-------------@@@@@@!** --@@@@!!!!!;;-.;..@------@...............::;!@** '@@@!!!!!!!;;;;;;;.....;@@.................:;;;;;;!@** @@@!!!!!!!;;;;;;:::.......................:;;;;;;;;;!@** -@@!!!!;;::::....................................;;:;!@** --@@!!:;;:::...................................;:;!@** ---@!!!!;::: :::..................................@** ------!!!!!;:::::::::..........................@** ----------!!!;;:::::::..:::::..........@** -------------:::::::::::...........@** ----------------::::::::.......@** -------------------:::::..@** ----------------------..@** ----------------------.! ----------------------.* ----------------------.* ---------------------.* ----------------------.* -----------------------.* ------------------------.* -------------------------.* """.format(nombre, acompanante, ninos, bus, consulta, email) toaddrs = to if email is not None: toaddrs = to + [email] #smtpserver.sendmail(gmail_user, toaddrs, header + msg) #smtpserver.close() outer = MIMEMultipart('related') outer['From'] = gmail_user outer['To'] = ", ".join(toaddrs) outer['CC'] = email outer['Subject'] = '[BODA CLAUNOEL - Invitacion Confirmada] {}\n'.format(nombre) #body = MIMEText(msg) # convert the body to a MIME compatible string #outer.attach(body) msgAlternative = MIMEMultipart('alternative') outer.attach(msgAlternative) # We reference the image in the IMG SRC attribute by the ID we give it below htmlMsg=""" <html> <body> <img src="cid:image1"> <br/> <br/> <br/> <br/> <i><b>Invitacion Confirmada</b></i> <br/> <br/> Muchas gracias por compartir con nosotros una noche tan especial. <br/> Esperamos que te diviertas y te contagies de nuestra felicidad y buen ambiente. <br/> <br/> <br/> <b> Nombre :</b> <i>{}</i> <br/> <b> Acompanante :</b> <i>{}</i> <br/> <b> Ninos :</b> <i>{}</i> <br/> <b> Bus :</b> <i>{}</i> <br/> <b> Consulta :</b> <i>{}</i> <br/> <b> email :</b> <i>{}</i> <br/> <br/> <br/> <i>Nos vemos el dia <b>23 de Junio</b> a las <b>21:00</b> en <a href="https://goo.gl/maps/dv7HdHYoKaN2"><b>El Hornillero</b></i></a> <br/> <br/> <br/> <br/> Recuerda que tienes toda la informacion necesaria en <a href="http://claunoel.cyberlove.us/">http://claunoel.cyberlove.us/</a> <br/> o puedes llamarnos si necesitas cualquier cosa. <br/> <br/> <i>Claudia :</i> <a href="tel:644-340-248"><b>644340248</b></a> <br/> <i>Oscar Noel :</i> <a href="tel:665-144-704"><b>665144704</b></a> <br/> <body> <html> """.format(nombre, acompanante, ninos, bus, consulta, email) msgText = MIMEText(htmlMsg, 'html') msgAlternative.attach(msgText) # This example assumes the image is in the current directory fp = open('static/img/intro-bg.jpg', 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<image1>') msgImage.add_header('Content-Disposition', 'inline', filename='intro-bg.jpg') outer.attach(msgImage) composed = outer.as_string() smtpserver.sendmail(gmail_user, toaddrs, composed) smtpserver.close() except: print('Error enviando mail') traceback.print_exc(file=sys.stdout) #return render_template('flash.html', message='Error enviando confirmacion\nPor favor intentelo de nuevo.') return render_template('index.html') #msg="Asistencia confimada! Gracias por venir: {}".format(form.username.data) #return render_template('flash.html', message=msg) return render_template('index.html') return render_template('index.html')
msg = MIMEMultipart('mixed') msg['Subject'] = subject msg['From'] = '[email protected] <*****@*****.**>' # 收件人为多个收件人,通过join将列表转换为以;为间隔的字符串 msg['To'] = ";".join(receiver) msg['Date'] = str(datetime.datetime.now()) # 构造文字内容 text = "Hi!\nHow are you?" text_plain = MIMEText(text, 'plain', 'utf-8') msg.attach(text_plain) # 构造图片链接 sendimagefile = open('BW1_NETVALUE_PIC.jpg', 'rb').read() image = MIMEImage(sendimagefile) image.add_header('Content-ID', '<image1>') image["Content-Disposition"] = 'attachment; filename="BW1_NETVALUE.jpg"' msg.attach(image) # 构造html # 发送正文中的图片:由于包含未被许可的信息,网易邮箱定义为垃圾邮件,报554 DT:SPM :<p><img src="cid:image1"></p> html = """ <html> <head></head> <body> <p>Hi!<br> How are you?<br> Here is the <a href="http://www.baidu.com">link</a> you wanted.<br> </p> </body> </html>
def send_otp(request): if request.user.is_admin: user = request.user if user.email_not_verified == True: user.email_not_verified = False user.save() if request.user.is_admin: return redirect('home_page') otp_generated = random.randint(100000, 999999) otp_clean = str(otp_generated) global main_otp main_otp = otp_clean user_email = request.user.email user_first_name = request.user.first_name user_password = request.user.user_raw_p to = user_email subject = 'Cryptocurrency Investorsllc Account Activation Code(OTP)' first_name = user_first_name image_path = "static/cryptocurrencyinvestorsllc/assets/img/ban-white.png" image_name = 'ban-white.png' message = f"DEAR INVESTOR {0},\n\n Our warmest congratulations on your new account opening. This only shows that you have grown your business well. I pray for you to be prosperious. \n\n You have taken this path knowing that you can do it. Good luck with your new business. I wish you all the success and fulfillment towards your goal.\n\n {1} is your activation code. \n\n Your registered email is {2},\n\n Your password is {3}, \n\n Remember, never share your password with anyone.\n\n Kind Regards, \n\n The Cryptocurrency Investorsllc Team. ".format( first_name, main_otp, user_email, user_password) html_message = f""" <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Activation Code</title> <meta name="viewport" content="width = 375, initial-scale = -1"> </head> <body style="background-color: #ffffff; font-size: 16px;"> <center> <table align="center" border="0" cellpadding="0" cellspacing="0" style="height:100%; width:600px;"> <!-- BEGIN EMAIL --> <tr> <td align="center" bgcolor="#ffffff" style="padding:30px"> <img src='cid:{image_name}'/> <p style="text-align:left">DEAR INVESTOR {first_name},<br><br> <span style="color:green"> Our warmest congratulations on your new account opening, This only shows that you have grown your business well. I pray for you to be prosperous</span>.<br><br> You have taken this path knowing that you can do it. Good luck with your new business. I wish you all the success and fulfillment towards your goal.<br><br> {main_otp} is your activation code.<br><br> Your registered email is {user_email}.<br><br> Your password is {user_password}<br><br> <span style="color:red">Remember, never share your password with anyone.</span><br><br> Kind Regards,<br> <b>The Cryptocurrency Investorsllc Team.</b> </p> </td> </tr> </tbody> </table> </center> </body> </html> """ recipient_list = [ to, ] sender = 'Cryptocurrencyinvestorsllc [email protected]' def send_email(subject, message, html_message=None, sender=sender, recipent=recipient_list, image_path=None, image_name=None): email = EmailMultiAlternatives(subject=subject, body=message, from_email=sender, to=recipient_list) if all([html_message, image_path, image_name]): email.attach_alternative(html_message, "text/html") email.content_subtype = 'html' email.mixed_subtype = 'related' image_path = "static/cryptocurrencyinvestorsllc/assets/img/ban-white.png" with open(image_path, 'r') as f: image = MIMEImage(f.read()) image.add_header('Content-ID', '<{name}>'.format(name='ban-white.png')) image.add_header('Content-Disposition', 'inline', filename='ban-white.png') email.attach(image) image.add_header('Content-ID', f"<{image_name}>") email.send() # send_mail( subject, message=message, html_message=html_message,from_email=sender, recipient_list=recipient_list) email = EmailMultiAlternatives(subject=subject, body=message, from_email=sender, to=recipient_list) if all([html_message, image_path, image_name]): email.attach_alternative(html_message, "text/html") email.content_subtype = 'html' email.mixed_subtype = 'related' with open(image_path, 'rb') as f: image = MIMEImage(f.read()) image.add_header('Content-ID', '<{name}>'.format(name=image_name)) image.add_header('Content-Disposition', 'inline', filename=image_name) email.attach(image) image.add_header('Content-ID', f"<{image_name}>") email.send() return render(request, 'account/send_otp.html')
msg["From"] = email_from msg["To"] = email_to # 2.1. Текст # Добавление вложения в контейнер, используя метод attach контейнера. # Для MIMEText если вместо HTML используется текст, # вторым параметром будет "plain". msg.attach(MIMEText(html, "html")) # 2.2. Файл - Рисунок img_filename = input("Имя файла с рисунком: ") with open(img_filename, "rb") as image: attachment = MIMEImage(image.read()) # Обозначаем, что это вложение и указываем имя attachment.add_header("Content-Disposition", "attachment", filename=os.path.basename(img_filename)) msg.attach(attachment) # 2.3. Файл - Код with open(__file__, "rb") as f: attachment = MIMEApplication(f.read()) # Необходимо обозначить, что это вложение и его имя attachment.add_header("Content-Disposition", "attachment", filename=os.path.basename(__file__)) msg.attach(attachment) # 3. Подключение к серверу и отправка письма server = smtplib.SMTP("smtp.gmail.com", 587) try:
msg['From'] = Header('Python') # 发件人 msg['To'] = Header(i) # 收件人 msg['Subject'] = Header('test') # 邮件标题 part1 = MIMEText(open(r'QQ邮箱群发邮件\三国演义.txt', 'rb').read(), 'base64', 'utf-8') part1.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', '测试1.txt')) part2 = MIMEText(open(r'QQ邮箱群发邮件\test.docx', 'rb').read(), 'base64', 'utf-8') part2.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', '测试2.docx')) part3 = MIMEImage(open(r'QQ邮箱群发邮件\bird1.gif', 'rb').read()) part3.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', '测试3.gif')) part4 = MIMEApplication(open(r'QQ邮箱群发邮件\牛牛.zip', 'rb').read()) part4.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', '测试4.zip')) part5 = MIMEText('Test:send by Python', 'plain', 'utf-8') # 正文 msg.attach(part1) msg.attach(part2) msg.attach(part3) msg.attach(part4) msg.attach(part5) server.sendmail(my_mail, i, msg.as_string()) server.close()
#发送人,接收人 sender = '*****@*****.**' pwd = 'lighsgybbsmmicia' #请自行登陆邮箱打开SMTP服务,会自动生成第三方授权码,不是登陆密码! receiver = '*****@*****.**' #格式化的署名和接收人信息 message = MIMEMultipart() message['From'] = _format_addr('这是xx<%s>' % sender) message['To'] = _format_addr(receiver) message['Subject'] = ('我是标题!!') message.attach( MIMEText( '<html><body>' + '<h1>Hello</h1>' + '<p>礼物<img src="cid:Imgid">' + '</body></html>', 'html', 'utf-8')) #MIMEImage,只要打开相应图片,再用read()方法读入数据,指明src中的代号是多少,如这里是'Imgid’,在HTML格式里就对应输入。 with open('./github-octocat.jpg', 'rb') as f: mime = MIMEImage(f.read()) mime.add_header('Content-ID', 'Imgid') message.attach(mime) #发送邮件! try: smtpobj = smtplib.SMTP_SSL('smtp.qq.com', 465) smtpobj.login(sender, pwd) smtpobj.sendmail(sender, [receiver], message.as_string()) print('邮件发送成功') smtpobj.quit() except smtplib.SMTPException as e: print('邮件发送失败,Case:%s' % e)
def send_email_smtp(to, subject, html_content, config, files=None, data=None, images=None, dryrun=False, cc=None, bcc=None, mime_subtype='mixed'): """ Send an email with html content, eg: send_email_smtp( '*****@*****.**', 'foo', '<b>Foo</b> bar',['/dev/null'], dryrun=True) """ smtp_mail_from = config.get('SMTP_MAIL_FROM') to = get_email_address_list(to) msg = MIMEMultipart(mime_subtype) msg['Subject'] = subject msg['From'] = smtp_mail_from msg['To'] = ', '.join(to) msg.preamble = 'This is a multi-part message in MIME format.' recipients = to if cc: cc = get_email_address_list(cc) msg['CC'] = ', '.join(cc) recipients = recipients + cc if bcc: # don't add bcc in header bcc = get_email_address_list(bcc) recipients = recipients + bcc msg['Date'] = formatdate(localtime=True) mime_text = MIMEText(html_content, 'html') msg.attach(mime_text) # Attach files by reading them from disk for fname in files or []: basename = os.path.basename(fname) with open(fname, 'rb') as f: msg.attach( MIMEApplication( f.read(), Content_Disposition="attachment; filename='%s'" % basename, Name=basename)) # Attach any files passed directly for name, body in (data or {}).items(): msg.attach( MIMEApplication( body, Content_Disposition="attachment; filename='%s'" % name, Name=name, )) # Attach any inline images, which may be required for display in # HTML content (inline) for msgid, body in (images or {}).items(): image = MIMEImage(body) image.add_header('Content-ID', '<%s>' % msgid) image.add_header('Content-Disposition', 'inline') msg.attach(image) send_MIME_email(smtp_mail_from, recipients, msg, config, dryrun=dryrun)
def addimg(src,imgid): fp = open(src, 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', imgid) return msgImage