def funcSendmail(title, receiver, body, attachment_list): msg = MIMEMultipart() msg["From"] = sender msg["To"] = receiver msg["Subject"] = title # body="" for attachment in attachment_list: # body+='<img src="cid:' + attachment + '.jpg"><br>' # with open(attachment, 'rb') as fp: # img = MIMEImage(fp.read()) with open(attachment, "rb") as fil: part = MIMEApplication(open(attachment, "rb").read()) part.add_header('Content-Disposition', 'attachment', filename=attachment) msg.attach(part) # img.add_header('Content-ID', attachment) # msg.attach(img) msgText = MIMEText(body, 'html') msg.attach(msgText) # Added, and edited the previous line # for attachment in attachment_list['list'].split() : # fp = open(attachment+'.jpg', 'rb') # img = MIMEImage(fp.read()) # fp.close() # img.add_header('Content-ID', attachment) # msg.attach(img) #print msg.as_string() s = smtplib.SMTP(smtpserver) s.sendmail(msg["From"], msg["To"], msg.as_string()) s.quit()
def send(): for table in generate_xls.generate_empty_tables(): group_name = table['group_name'] course = table['course'] spec_name = table['spec_name'] elder_name = table['elder_name'] elder_mail = table['elder_mail'] attachment = table['xls_file'] from_adr = u'ОНПУ <{0:s}@gmail.com>'.format(m_user) to_adr = u'Старостам групп <{0:s}>'.format(elder_mail) msg = MIMEMultipart() msg['Subject'] = 'Журнал посещаемости' msg['From'] = from_adr msg['To'] = to_adr msg_txt = MIMEText(u'''Здрвствуйте, ув. %s, староста группы %s. \n\nЗаполните приложенный файл и пришлите обратно не позднее %s.%s.%s.\n\nС уважением, ОНПУ.''' % (elder_name, group_name, date.today().year, date.today().month, (date.today().day + 7)), 'plain', 'utf-8') msg.preamble = ' ' attach = MIMEApplication(open(attachment, 'rb').read()) attach.add_header('Content-Disposition', 'attachment', filename=('%s_%s_%s.xls' % (group_name, course, spec_name))) msg.attach(attach) msg.attach(msg_txt) server = smtplib.SMTP('smtp.gmail.com', "587") server.set_debuglevel(1) server.starttls() server.login(m_user, m_pass) server.sendmail(from_adr, to_adr, msg.as_string()) server.quit()
def send_ses(fromaddr, subject, body, recipient, attachment=None, filename=''): """Send an email via the Amazon SES service. Example: send_ses('[email protected], 'greetings', "Hi!", '[email protected]) Return: If 'ErrorResponse' appears in the return message from SES, return the message, otherwise return an empty '' string. """ msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = fromaddr msg['To'] = recipient msg.attach(MIMEText(body)) if attachment: part = MIMEApplication(attachment) part.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(part) conn = boto.connect_ses() result = conn.send_raw_email(msg.as_string()) return result if 'ErrorResponse' in result else ''
def send_mail2(to_list,sub,content,attach_file="0128/result.txt"): ############# #to_list为收件人 #sub为邮件标题 #content为邮件内容 ############### #设置服务器,用户名、口令以及邮箱的后缀 mail_host="smtp.qq.com" mail_user="******" mail_pass="******" mail_postfix="qq.com" me=mail_user+"<"+mail_user+"@"+mail_postfix+">" msg=MIMEMultipart() msg['Subject'] = sub msg['From'] = me msg['To'] = to_list att = MIMEApplication(file(attach_file, 'rb').read()) att["Content-Type"] = 'application/octet-stream' att.add_header('content-disposition','attachment',filename=attach_file) msg.attach(att) try: s = smtplib.SMTP() s.connect(mail_host) s.login(mail_user,mail_pass) s.sendmail(me, to_list, msg.as_string()) s.close() return True except Exception as e: print(e) return False pass
def BuildReport(job, files, buildTime): toaddr = job.email #toaddr = ["*****@*****.**"] msg = MIMEMultipart() msg['Subject'] = job.stream + " Build Report (" + job.arch + ")" msg['From'] = FROM_ADDRESS msg['To'] = str(toaddr).strip("[ ]"); msg['CC'] = str(CCList).strip("[ ]"); body = ReportBody.safe_substitute(stream = job.stream, arch = job.arch, vcconfig = job.type,\ changelog = job.changelog, type = job.type, clean = job.clean,\ repop = job.repop, time = buildTime) txt = MIMEText(body) msg.attach(txt) for file in files: file = file.strip("\n\r\t ") print "*** Attching file: " + file part = MIMEApplication(FormatError(file)) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) msg.attach(part) print "*** Sending email to " + str(toaddr) try : s = smtplib.SMTP(SMTPServer) #s.set_debuglevel(1) s.sendmail(FROM_ADDRESS, toaddr + CCList, msg.as_string()) s.close() except smtplib.SMTPException : print "*** Failed to send email" return
def sendmail(receivers, body, attachement): # Sending mail username = '******' password = '******' server = 'mail.' sender = 'kath@' #receivers = '@' try: msg = MIMEMultipart() msg['Subject'] = 'New Data File' msg['From'] = sender msg['To'] = receivers msg.preamble = 'New Data File' fp = open(attachement, 'rb') afile = MIMEApplication(fp.read()) filename = "Data-" + datetime.datetime.now().strftime("%y-%m-%d-%H-%M") + ".csv" afile.add_header('Content-Disposition', 'attachment', filename=filename) fp.close() body = MIMEText(body, 'plain') msg.attach(body) msg.attach(afile) smtpObj = smtplib.SMTP(server) smtpObj.login(username, password) smtpObj.sendmail(msg['From'], msg['To'], msg.as_string()) print "Successfully sent email" except: print "Error: unable to send email" traceback.print_exc(file=sys.stdout)
def send(self): smtp = smtplib.SMTP() smtp.connect('smtp.mail.ru', 2525) smtp.login('*****@*****.**', 'gjjc2011') from_addr = "Stas Litvinenko <*****@*****.**>" to_addr = self.adress.get() subj = self.title.get() message_text = self.message.get('1.0', 'end') #date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" ) m=MIMEMultipart() m["to"]=to_addr m["from"]=from_addr m["subject"]=Header(subj, 'utf-8') ##m.add_header("subject", MIMEText(subj, 'plain', 'utf-8')) i = 0 # m2 = MIMEApplication() print(self.lbox.size()) while i < self.lbox.size(): path = self.lbox.get(i) (dirname, filename) = os.path.split(path) print(filename) fp = open(path, 'rb') m2 = MIMEApplication(fp.read()) m2.add_header('Content-Disposition', 'attachment', filename=filename) m.attach(m2) fp.close() i += 1 m.attach(MIMEText(message_text, 'plain', 'utf-8')) smtp.sendmail(from_addr, to_addr, m.as_string()) smtp.quit()
def send_email(account, mail_list, sub, content_html, append_list): ENCODE = 'utf-8' me = account.sender_name + "<"+account.user+">" msg = MIMEMultipart() msg['Subject'] = sub msg['From'] = me msg['BCC'] = ";".join(mail_list) msg_text = MIMEText(content_html, 'html', ENCODE) msg.attach(msg_text) print_t("Read Appends") for each_append in append_list: f = open(each_append, 'rb') f_basename = os.path.basename(each_append).encode(ENCODE) msg_append = MIMEApplication(f.read()) msg_append.add_header('Content-Disposition', 'attachment', filename=f_basename) msg.attach(msg_append) # -------------------------------------------------------------------------------------- s = imaplib.IMAP4(account.host) s.login(account.user, account.passwd)
def sendMcAfee(filename, help_text, email, name): try: #if ".zip" not in filename: compress(filename, filename + ".zip", "infected", 5) filename += ".zip" name += ".zip" name = name.encode("utf8") msg = MIMEMultipart( From=email, To="*****@*****.**", Subject="Potential virus", Date=formatdate(localtime=True) ) msg.attach(MIMEText(help_text)) with open(filename, 'rb') as archive: msg_attach = MIMEApplication( archive.read(), Name=name, ) msg_attach.add_header('Content-Disposition', 'attachment', filename=(Header(name, 'utf-8').encode())) msg.attach(msg_attach) smtp = smtplib.SMTP("smtp") smtp.sendmail(email, "*****@*****.**", msg.as_string()) smtp.close() return 0, "Success! %s" % name except Exception as e: logger.warning("MacAfee error: %s" % e) return 1, "Something went wrong: %s" % e
def _send(self, user, target, extra_context): extra_context['recipient'] = target t = Template(self.message) message = t.render(Context(extra_context)) html_content, attachments = self._convert_inline_images(message) txt_content = html2text(html_content) for attachment in self.attachments.all(): file_data = MIMEApplication(attachment.file.read()) file_data.add_header('Content-Disposition', 'attachment', filename=attachment.name) attachments.append(file_data) # Setup From email string. if(self.from_name): from_email = "{} <{}>".format(self.from_name, self.from_email) else: from_email = self.from_email reply_to_email= None if self.reply_to_email: if self.reply_to_name: reply_to_email = "{} <{}>".format(self.reply_to_name, self.reply_to_email) else: reply_to_email = self.reply_to_email return EmailRecord.objects.send_email(user, from_email, reply_to_email, target, self.subject, html_content, txt_content, attachments);
def send_mail(self, subject, text, files=[]): try: COMMASPACE = ', ' send_to = [self.admin_email] server = self.smtp assert type(send_to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = self.a_user msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject print('EMAIL send: %s'%text) msg.attach(MIMEText(text)) for f in files: part = MIMEApplication(open(f, 'rb').read()) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP_SSL(server,timeout=self.timeout) smtp.login(self.a_user,self.a_pw) smtp.sendmail(self.a_user, send_to, msg.as_string()) smtp.close() except BaseException as e: print (str(e))
def send_email(info, email, files, lfil=None, sub="CoreRep Results"): sender = '*****@*****.**' receivers = email message = MIMEMultipart() message['To'] = email message['From'] = "CoreRep Server <*****@*****.**>" message['Subject'] = sub body = MIMEText(info, 'html') message.attach(body) for f in files or []: try: with open(f, "rb") as fil: attach_file = MIMEApplication(fil.read()) except IOError: open(f, "w").close() with open(f, "rb") as fil: attach_file = MIMEApplication(fil.read()) attach_file.add_header('Content-Disposition', 'attachment', filename=f) message.attach(attach_file) try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message.as_string()) print "Successfully sent email" except smtplib.SMTPException: if lfil is not None: logtools.add_fatal_error(lfil, "UNABLE TO SEND EMAIL!!!") print "Error: unable to send email"
def upload_attachment(self, page_id, filename, file_content, **kwargs): """Uploads attachment.""" mime = MIMEMultipart("form-data") part = MIMEApplication(file_content, "octet-stream", encode_noop) part.add_header("Content-Disposition", "form-data", name="Filedata", filename=filename.encode("utf-8")) part.add_header("Content-Transfer-Encoding", "binary") mime.attach(part) # we don't want mime.as_string(), because the format is different # from the one we should use in HTTP requests # all we wanted is a proper boundary string boundary = mime.get_boundary() body = "\r\n".join( [ "--" + boundary, ('Content-Disposition: form-data; name="Filedata"; ' 'filename="{}"').format(filename.encode("utf-8")), # 'MIME-Version: 1.0', "Content-Type: application/octet-stream", # 'Content-Transfer-Encoding: binary', "", file_content, "--" + boundary + "--", "", ] ) path = "/pages/%d/attachments%s" % (page_id, self._create_argument(**kwargs)) headers = { "Authorization": "Basic %s" % self.auth_key, "Content-Type": "multipart/form-data; boundary=%s" % boundary, "Content-Length": str(len(body)), } try: return self._request("POST", path, body, headers) except SpringnoteException as ex: if ex.status >= 300 and ex.status < 400: # it's a redirect return True # TODO
def email_facture(): msg = MIMEMultipart() enc = 'latin-1' msg['Subject'] = request.form['subject'].encode(enc) msg['From'] = u'Société Roucet <*****@*****.**>'.encode(enc) to_list = re.split('[ ,;:\t\n]+', request.form['email_addresses']) msg['To'] = COMMASPACE.join(to_list) msg['Reply-to'] = '*****@*****.**' try: msg.attach(MIMEText(request.form['msg'].encode(enc), 'plain', enc)) except: msg.attach(MIMEText(request.form['msg'].encode('utf8'), 'plain', 'utf8')) if 'include_pdf' in request.form: out_fn = _generate_facture(g, request.form['no_commande_facture']) part = MIMEApplication(open(out_fn, "rb").read()) part.add_header('Content-Disposition', 'attachment', filename="facture_roucet.pdf") msg.attach(part) mailer = SMTP('mail.roucet.com', 587) mailer.login('*****@*****.**', SMTP_PW) mailer.sendmail(msg['From'], to_list, msg.as_string()) mailer.close() # if user is admin, set facture_est_envoyee to True, if repr, this will # be done in the next ajax call (to /representant/set_facture_est_envoyee) if not current_user.u['representant_id']: pg.update(g.db.cursor(), 'commande', set={'facture_est_envoyee': True}, where={'no_commande_facture': request.form['no_commande_facture']}) g.db.commit() return {'success': True}
def send_mail(mail_list, sub, content_html, append_list): ENCODE = 'utf-8' me = "刘泽宇" + "<"+MAIL_USER+">" msg = MIMEMultipart() msg['Subject'] = sub msg['From'] = me msg['BCC'] = ";".join(mail_list) msg_text = MIMEText(content_html, 'html', ENCODE) msg.attach(msg_text) print_t("Read Appends") for each_append in append_list: f = open(each_append, 'rb') f_basename = os.path.basename(each_append).encode(ENCODE) msg_append = MIMEApplication(f.read()) msg_append.add_header('Content-Disposition', 'attachment', filename=f_basename) msg.attach(msg_append) print_t("Start to connect.") s = smtplib.SMTP() s.connect(MAIL_HOST) #没网, 或DNS print_t("Connetc success") s.login(MAIL_USER, MAIL_PASS) #用户名密码错误 print_t("Before Send Email, there are {} receivers.".format(len(mail_list))) try: err_mail = s.sendmail(me, mail_list, msg.as_string()) except smtplib.SMTPRecipientsRefused, e: print("==============Catch SMTPRecipientsRefused Error================") print(e) print("-------") print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
def SendMail(mailist): '邮件发送函数' From = "*****@*****.**" ToList = ["*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**"] server = smtplib.SMTP("smtp.qq.com") server.login('870937931', 'zgsboy@888') msg = email.MIMEMultipart.MIMEMultipart() text_msg = email.MIMEText.MIMEText(u"数据发布日志", _charset="utf-8") msg.attach(text_msg) msg["Subject"] = u"每日土地统计" + curdate msg["From"] = From msg["To"] = ";".join(ToList) part = MIMEApplication(open(filename, 'rb').read()) part.add_header('Content-Disposition', 'attachment', filename='land' + curdate + '.xls') msg.attach(part) server.sendmail(From, ToList, msg.as_string()) server.close() sendmail()
def send_mail(mail_user, mail_to, sub): # msg = MIMEText(content, _subtype='plain') msg = MIMEMultipart() msg['Subject'] = sub msg['From'] = mail_user msg['To'] = mail_to #读取txt并显示于正文 msg.attach(MIMEText("每天访问前100名ip统计:")) msg.attach(MIMEText(content_ip)) msg.attach(MIMEText("每天访问/home主页前100名ip统计:")) msg.attach(MIMEText(content_ip_home)) #加载txt附件 att_ip = MIMEApplication(open('command_list', 'rb').read()) att_ip_home = MIMEApplication(open('command_list', 'rb').read()) att_ip.add_header('Content-Disposition', 'attachment', filename="ip.txt") att_ip_home.add_header('Content-Disposition', 'attachment', filename="ip_home.txt") # att["Content-Type"] = 'application/octet-stream' att_ip["Content-Disposition"] = 'download' msg.attach(att_ip) msg.attach(att_ip_home) try: s = smtplib.SMTP() s.connect(mail_host) s.login(mail_user, mail_pass) s.sendmail(mail_user, mail_to, msg.as_string()) s.close() return True except Exception, e: print e.message return False
def send(self, subject, content, tolist, cclist=[], plugins =[], is_proxy=False): '''发送邮件 Args: subject:标题 content:内容 tolist:收件人 cclist:抄送人 plugins:附件 is_proxy:是否代理发送 True:代理发送:不需要登录;False:非代理发送:需要登录 ''' msg = MIMEMultipart() msg.set_charset('utf-8') msg['from'] = self.user msg['to'] = ','.join(tolist) if cclist: msg['cc'] = ','.join(cclist) msg['subject'] = subject msg.attach( MIMEText(content, 'html', 'utf-8')) for plugin in plugins: f = MIMEApplication(plugin['content']) f.add_header('content-disposition', 'attachment', filename=plugin['subject']) msg.attach(f) s = smtplib.SMTP(self.smtp) s.set_debuglevel(smtplib.SMTP.debuglevel) if self.isauth: s.docmd("EHLO %s" % self.smtp) try: s.ehlo() s.starttls() except smtplib.SMTPException,e: pass
def sendmail(reqid): mailaddr = '*****@*****.**' with open(os.path.join(JSON_DIR, reqid), 'r') as f: s = f.read() mail = MIMEMultipart() mail['From'] = '*****@*****.**' mail['To'] = mailaddr mail['Subject'] = Header(u'Python.jp イベント登録の確認', 'utf-8') y = to_yaml(s) mail.attach(MIMEText(msg % (reqid, y), _charset='utf-8')) j = MIMEApplication(y.encode('utf-8'), 'octet-stream', encode_base64) j.add_header('Content-Disposition', 'attachment; filename="%s.yaml"' % reqid) mail.attach(j) p = subprocess.Popen([SENDMAIL, mailaddr], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) o, e = p.communicate(mail.as_string()) if p.returncode: print o, e, p.returncode return return True
def mail(mail_from, mail_password, mail_to, content, fpath_list): # 将多个文件发送至多个接收邮箱 mail_server = mail_server_check(mail_from) # 确定发送邮箱的smtp服务地址 if mail_server: # 确认发送邮箱的smtp地址 msg = MIMEMultipart() # 构建邮件 msg['Subject'] = Header(u'双犬:[RR]随机用户最后登录时间', 'utf-8') # 邮件标题 msg['From'] = mail_from # 邮件发送地址 msg['To'] = ",".join(mail_to) # 邮件接收地址 text_part = MIMEText(content, 'plain', 'utf-8') # 构建以content变量(完成状态)为基础的正文部分 msg.attach(text_part) # 将正文部分补充至邮件中 for file_each in fpath_list: # 对附件列表进行遍历 f = open(file_each, "rb") # 以二进制模式打开将作为附件的文件 file_content = f.read() # 读取文件内容 f.close() # 关闭文件 file_part = MIMEApplication(file_content) # 构建附件部分 file_part.add_header('Content-Disposition', 'attachment', filename = file_each) # 添加附件头信息,以扩展名决定对方的文件打开方式 msg.attach(file_part) # 将附件补充至邮件中 try: # 尝试发送邮件 smtp = smtplib.SMTP(mail_server, 25) # 以25端口构建smtp服务 smtp.ehlo() # 确认smtp服务 smtp.starttls() # 创建TLS连接 smtp.ehlo() # 再次确认smtp服务 smtp.login(mail_from, mail_password) # 登录发送邮箱 smtp.sendmail(mail_from, mail_to, msg.as_string()) # 发送邮件 smtp.quit() # 注销邮箱,退出smtp服务 return u"通知/输出已放出" # 报告通知已经发出 except Exception as ee: # 邮件发送失败 return u"对于" +each_to + u"的通知放出失败:" + str(ee) # 报告邮件发送失败及原因
def make_file_payload(name, content): payload = MIMEApplication(content.read()) payload.add_header( "Content-Disposition", "form-data", name=name, filename=name) names = name, getattr(content, "name", None) payload.set_type(get_content_type(*names)) return payload
def send_mail(**kwargs): ''' :param f: 附件路径 :param to_addr:发给的人 [] :return: ''' from_addr = kwargs["mail_user"] password = kwargs["mail_pass"] # to_addr = "*****@*****.**" smtp_server = kwargs["mail_host"] msg = MIMEMultipart() # msg = MIMEText('hello, send by Python...', 'plain', 'utf-8') msg['From'] = _format_addr('来自<%s>接口测试' % from_addr) msg['To'] = _format_addr(' <%s>' % kwargs["to_addr"]) msg['Subject'] = Header(kwargs["header_msg"], 'utf-8').encode() msg.attach(MIMEText(kwargs["attach"], 'plain', 'utf-8')) if kwargs.get("report", "0") != "0": part = MIMEApplication(open(kwargs["report"], 'rb').read()) part.add_header('Content-Disposition', 'attachment', filename=('gb2312', '', kwargs["report_name"])) msg.attach(part) server = smtplib.SMTP_SSL(smtp_server, kwargs["port"]) server.set_debuglevel(1) server.login(from_addr, password) server.sendmail(from_addr, kwargs["to_addr"], msg.as_string()) server.quit()
def send_email(subject, text, log_tar): if options.email is None: do_print("not sending email because the recipient is not set") do_print("the text content would have been:\n\nSubject: %s\n\nTs" % (subject, text)) return outer = MIMEMultipart() outer['Subject'] = subject outer['To'] = options.email outer['From'] = options.email_from outer['Date'] = email.utils.formatdate(localtime = True) outer.preamble = 'Autobuild mails are now in MIME because we optionally attach the logs.\n' outer.attach(MIMEText(text, 'plain')) if options.attach_logs: fp = open(log_tar, 'rb') msg = MIMEApplication(fp.read(), 'gzip', email.encoders.encode_base64) fp.close() # Set the filename parameter msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(log_tar)) outer.attach(msg) content = outer.as_string() s = smtplib.SMTP(options.email_server) s.sendmail(options.email_from, [options.email], content) s.set_debuglevel(1) s.quit()
def sendEmail(self, recipients, body, subject, files=None): print "sendEmail" try: s = smtplib.SMTP('smtp.relay.com') s.set_debuglevel(1) if files: msg = MIMEMultipart() msg.attach(MIMEText(body)) with open(files, 'rb') as f: part = MIMEApplication(f.read()) part.add_header('Content-Disposition', 'attachment', filename="%s" % files) msg.attach(part) else: msg = MIMEText(body) sender = '*****@*****.**' msg['Subject'] = subject msg['From'] = sender msg['To'] = ", ".join(recipients) s.sendmail(sender, recipients, msg.as_string()) s.close() except smtplib.SMTPException as e: print "error: %s" % e
def sendmail(reqid): with open(os.path.join(JSON_DIR, reqid), 'r') as f: s = f.read() rec = json.loads(s) mail = MIMEMultipart() mail['From'] = '*****@*****.**' mail['To'] = MAILADDR mail['Subject'] = Header(u'Python.jp イベント登録の確認', 'utf-8') rest = to_rest(rec) mail.attach(MIMEText(msg % (reqid, rec['mailaddr'], rest), _charset='utf-8')) j = MIMEApplication(rest.encode('utf-8'), 'octet-stream', encode_base64) j.add_header('Content-Disposition', 'attachment; filename="%s.rest"' % reqid) mail.attach(j) p = subprocess.Popen([SENDMAIL, MAILADDR], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) o, e = p.communicate(mail.as_string().encode('utf-8')) if p.returncode: return return True
def send ( self, sSubject, sContent, lsTo, lsCc = [], lsPlugin = [] ): mit = MIMEMultipart() mit['from'] = self.sender mit['to'] = ','.join( lsTo ) if lsCc: mit['cc'] = ','.join( lsCc ) codeSubject, codeContent, codePlugin = self._parserSend(sSubject, sContent, lsPlugin) mit.attach( MIMEText( codeContent, 'html', 'utf-8' ) ) mit['subject'] = codeSubject for plugin in codePlugin: mitFile = MIMEApplication( plugin['content'], ) mitFile.add_header( 'content-disposition', 'attachment', filename=plugin['subject'] ) mit.attach( mitFile ) try: server = smtplib.SMTP( self.smtp ) #server.set_debuglevel(smtplib.SMTP.debuglevel) if self.bSmtpAuth: server.docmd( "EHLO server" ) server.starttls() server.login( self.sender, self.pwd ) server.sendmail( self.sender, lsTo , mit.as_string() ) server.close() except Exception as e: print e.args,e.message finally: pass
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_email(self, market_id, email): # отправитель me = '*****@*****.**' # получатель you = email # текст письма text = 'Это письмо к вам пришло потому что в файле выгрузки есть не валидные продукты список их прикреплен в файле' text = msg = MIMEText(text, _charset="utf-8") # заголовок письма subj = 'Hello!!' # параметры SMTP-сервера server = "yottos.com" # "smtp.mail.ru" port = 26 user_name = "*****@*****.**" user_passwd = "57fd8824" msg = MIMEMultipart() msg['Subject'] = subj msg['From'] = me msg['To'] = you path = 'parseryml/public/not_valid/' + str(market_id) + '.txt' attach = MIMEApplication(open(path, 'r').read()) attach.add_header('Content-Disposition', 'attachment', filename='errors.txt') msg.attach(text) msg.attach(attach) s = smtplib.SMTP(server, port) s.starttls() s.set_debuglevel(5) s.login(user_name, user_passwd) s.sendmail(me, you, msg.as_string()) s.quit()
def send_mail(Memail): ''' :param f: 附件路径 :param to_addr:发给的人 [] :return: ''' from_addr = Memail.mail_user password = Memail.mail_pass # to_addr = "*****@*****.**" smtp_server =Memail.mail_host msg = MIMEMultipart() # msg = MIMEText('hello, send by Python...', 'plain', 'utf-8') msg['From'] = _format_addr('施坤<%s>' % from_addr) msg['To'] = _format_addr('大人 <%s>' % Memail.to_addr) msg['Subject'] = Header(Memail.headerMsg, 'utf-8').encode() msg.attach(MIMEText(Memail.attach, 'plain', 'utf-8')) part = MIMEApplication(open(Memail.report, 'rb').read()) part.add_header('Content-Disposition', 'attachment', filename=Memail.report) msg.attach(part) server = smtplib.SMTP_SSL(smtp_server, Memail.port) server.set_debuglevel(1) server.login(from_addr, password) server.sendmail(from_addr, Memail.to_addr, msg.as_string()) server.quit()
def send_email(smtp,pdfWriter,filename,names): # write the file filename += '.pdf' wf = file(filename,"wb") pdfWriter.write(wf) wf.close() # send email to recipients msg = MIMEMultipart() msg['From'] = '*****@*****.**' msg['To'] = ', '.join(names[prevName]) msg['Subject'] = 'PDF from Vendor' # message text msg.attach(MIMEText("See attachment!")) # read the recent file and add as email attachment fp = open(filename,'rb') attach = MIMEApplication(fp.read(),'pdf') attach.add_header('Content-Disposition','attachment',filename=filename) msg.attach(attach) fp.close() # Send the email smtp.sendmail(msg['From'],msg['To'],msg.as_string())
for to_addrs in email_list: msg = MIMEMultipart() msg['Subject'] = "Hello How are you ?" msg['From'] = from_addr msg['To'] = to_addrs # Attach HTML to the email body = MIMEText(html, 'html') msg.attach(body) # Attach Cover Letter to the email cover_letter = MIMEApplication(open("file1.pdf", "rb").read()) cover_letter.add_header('Content-Disposition', 'attachment', filename="file1.pdf") msg.attach(cover_letter) # Attach Resume to the email cover_letter = MIMEApplication(open("file2.pdf", "rb").read()) cover_letter.add_header('Content-Disposition', 'attachment', filename="file2.pdf") msg.attach(cover_letter) try: send_mail(username, password, from_addr, to_addrs, msg) print "Email successfully sent to", to_addrs except SMTPAuthenticationError: print 'SMTPAuthenticationError'
def _sendMail( region_name: str, recipients: list, subject: str, body_html: str = None, body_text: str = None, attachments: list = None, ) -> dict: # Create ses client. if isDocker(): client = boto3.client( "ses", region_name=region_name, endpoint_url=LOCAL_END_POINT_URL, ) client.verify_email_identity(EmailAddress=SENDER_EMAIL) else: client = boto3.client("ses", region_name=region_name) # Create sender info environment: str = "" if isLocal() is True: environment = "[local]" if isDev() is True: environment = "[develop]" if isSt() is True: environment = "[staging]" sender_name = Header(f"{environment}{SENDER_NAME}".encode("iso-2022-jp"), "iso-2022-jp").encode() sender: str = f"{sender_name} <{SENDER_EMAIL}>" # Create a multipart/mixed parent container. msg = MIMEMultipart("mixed") # Add subject, from and to lines. msg["subject"] = subject msg["From"] = sender msg["To"] = ", ".join(recipients) # Create a multipart/alternative child container. msg_body = MIMEMultipart("alternative") # Set html body. if body_html is not None: # The HTML body of the email. htmlpart = MIMEText(body_html.encode(CHARSET), "html", CHARSET) msg_body.attach(htmlpart) # Set text body. if body_text is not None: # The email body for recipients with non-HTML email clients. textpart = MIMEText(body_text.encode(CHARSET), "plain", CHARSET) msg_body.attach(textpart) # Attach files. if attachments is not None and len(attachments) != 0: for attachment in attachments: att = MIMEApplication(open(attachment, "rb").read()) att.add_header( "Content-Disposition", "attachment", filename=os.path.basename(attachment), ) msg.attach(att) # Attach the multipart/alternative child container to the multipart/mixed # parent container. msg.attach(msg_body) # Send the email. # Provide the contents of the email. response = client.send_raw_email(Source=sender, Destinations=recipients, RawMessage={"Data": msg.as_string()}) return response
from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr,formataddr from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart import smtplib def format_addr(s): name,addr= parseaddr(s) return formataddr((Header(name,'utf-8').encode(),addr)) for_addr = '*****@*****.**' passwd = '*******' to_addr = '*****@*****.**' smtp_server = 'smtp.163.com' msg = MIMEMultipart() msg['From']=format_addr('一号爬虫<%s>'%for_addr) msg['To']=format_addr('管理员<%s>'%to_addr) msg['Subject']=Header('一号爬虫运行','utf-8').encode() msg.attach(MIMEText('hello ,this is axin','plain','utf-8')) part = MIMEApplication(open('D:\python3.6.5\day1.py','rb').read()) part.add_header('Content-Disposition','attachment',filename='邮件.py') msg.attach(part) server=smtplib.SMTP(smtp_server,25) server.login(for_addr,passwd) server.sendmail(for_addr,[to_addr],msg.as_string()) print('邮件发送成功') server.quit()
def send_logs(): os.system("/usr/sbin/logwatch > /tmp/logwatch.log") # Requirements from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email.mime.application import MIMEApplication from email.utils import COMMASPACE, formatdate from email import encoders import smtplib import mimetypes smtp_server = 'smtp.gmail.com' smtp_port = 587 from_address = '*****@*****.**' to_address = '*****@*****.**' subject_header = 'Webserver Backup & Log Report {}'.format( strftime("%m-%d-%Y")) attachment = '/tmp/logwatch.log' body = '' for line in open('/repo/last_update.log'): body += line m = MIMEMultipart() m["To"] = to_address m["From"] = from_address m["Subject"] = subject_header try: ctype, encoding = mimetypes.guess_type(attachment) print(ctype, encoding) maintype, subtype = ctype.split('/', 1) print(maintype, subtype) except: pass m.attach(MIMEText(body)) msg = MIMEApplication(open(attachment, 'rb').read()) msg.add_header( 'Content-Disposition', 'attachment; filename="{}"'.format(os.path.basename(attachment))) m.attach(msg) # Connect to Gmail outgoing = smtplib.SMTP(smtp_server, smtp_port) #port 465 or 587 # Gmail uses SSL by default outgoing.ehlo() outgoing.starttls() outgoing.ehlo() # Authenticate outgoing.login(from_address, 'SECRET PASSWORD GOES HERE') # Send E-mail outgoing.sendmail(from_address, to_address, m.as_string()) # Cleanup outgoing.quit()
def create_message_with_attachment(sender, to, subject, message_text, file, file2=None): message = MIMEMultipart('mixed') message['to'] = to message['from'] = sender message['subject'] = subject msg = MIMEText(message_text, 'html') message.attach(msg) #message.attach(MIMEText("test", 'application/pdf')) # print(file) # if os.path.isfile(file): # print("exists") #content_type, encoding = mimetypes.guess_type(file) #print(content_type) #print(stop) #if content_type is None or encoding is not None: # content_type = 'application/octet-stream' #main_type, sub_type = content_type.split('/', 1) #print(main_type) #print(stop) # main_type = "xxxx" # if main_type == 'text': # fp = open(file, 'rb') # msg = MIMEText(fp.read(), _subtype=sub_type) # fp.close() # elif main_type == 'image': # fp = open(file, 'rb') # msg = MIMEImage(fp.read(), _subtype=sub_type) # fp.close() # elif main_type == 'audio': # fp = open(file, 'rb') # msg = MIMEAudio(fp.read(), _subtype=sub_type) # fp.close() # else: #fp = open(file, 'rb') #msg = MIMEBase(main_type, sub_type) #msg.set_payload(fp.read()) #fp.close() with open(file, "rb") as f: attach = MIMEApplication(f.read(), _subtype="pdf") filename = os.path.basename(file) attach.add_header('Content-Disposition', 'attachment', filename=filename) #message.attach(msg) message.attach(attach) if file2 != None: # Also attach text file print("Attach text file") with open(file2, "rb") as f: attach = MIMEApplication(f.read(), _subtype="txt") filename = os.path.basename(file2) attach.add_header('Content-Disposition', 'attachment', filename=filename) #message.attach(msg) message.attach(attach) #return {'raw': base64.urlsafe_b64encode(message.as_string())} return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}
# Turn these into plain/html/img/file MIMEText objects with open('test.png', 'rb') as fob: img = fob.read() fob.close() with open('test.zip', 'rb') as fob: zips = fob.read() fob.close() part1 = MIMEText(text, "plain") part2 = MIMEText(html, "html") part3 = MIMEImage(img) part3.add_header('Content-Disposition', 'attachment', filename="test.png") part4 = MIMEApplication(zips) part4.add_header('Content-Disposition', 'attachment', filename="test.zip") # Add all parts to MIMEMultipart message # The email client will try to render the last part first message.attach(part1) message.attach(part2) message.attach(part3) message.attach(part4) # Create secure connection with server and send email context = ssl.create_default_context() with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, message.as_string()) #server.close() #server.logout()
def send_request(self, service, args={}, file_args=None): ''' service: string args: dict ''' if self.session is not None: args.update({'session': self.session}) print('Python:', args) json = python2json(args) print('Sending json:', json) url = self.get_url(service) print('Sending to URL:', url) # If we're sending a file, format a multipart/form-data if file_args is not None: m1 = MIMEBase('text', 'plain') m1.add_header('Content-disposition', 'form-data; name="request-json"') m1.set_payload(json) m2 = MIMEApplication(file_args[1], 'octet-stream', encode_noop) m2.add_header( 'Content-disposition', 'form-data; name="file"; filename="%s"' % file_args[0]) mp = MIMEMultipart('form-data', None, [m1, m2]) # Make a custom generator to format it the way we need. from cStringIO import StringIO from email.generator import Generator class MyGenerator(Generator): def __init__(self, fp, root=True): Generator.__init__(self, fp, mangle_from_=False, maxheaderlen=0) self.root = root def _write_headers(self, msg): # We don't want to write the top-level headers; # they go into Request(headers) instead. if self.root: return # We need to use \r\n line-terminator, but Generator # doesn't provide the flexibility to override, so we # have to copy-n-paste-n-modify. for h, v in msg.items(): print(('%s: %s\r\n' % (h, v)), end='', file=self._fp) # A blank line always separates headers from body print('\r\n', end='', file=self._fp) # The _write_multipart method calls "clone" for the # subparts. We hijack that, setting root=False def clone(self, fp): return MyGenerator(fp, root=False) fp = StringIO() g = MyGenerator(fp) g.flatten(mp) data = fp.getvalue() headers = {'Content-type': mp.get('Content-type')} else: # Else send x-www-form-encoded data = {'request-json': json} print('Sending form data:', data) data = urlencode(data) print('Sending data:', data) headers = {} request = Request(url=url, headers=headers, data=data) try: f = urlopen(request) txt = f.read() print('Got json:', txt) result = json2python(txt) print('Got result:', result) stat = result.get('status') print('Got status:', stat) if stat == 'error': errstr = result.get('errormessage', '(none)') raise RequestError('server error message: ' + errstr) return result except HTTPError as e: print('HTTPError', e) txt = e.read() open('err.html', 'wb').write(txt) print('Wrote error text to err.html')
def send_email(self): try: self.receiver = self.param_3.get() self.subject = self.param_4.get() self._send_text = self.param_5.get("0.0", "end") except Exception as e: print "RECEIVER INTO ERROR ->", str(e) print self.receiver, self.subject, self._send_text # 加入文本消息 msg = MIMEMultipart() msg['From'] = 'WUD_EMAIL_SYSTEM <' + self.user + '>' msg['To'] = self.receiver msg['Subject'] = self.subject _send_text = Encryption().Encry_text(str(self._send_text)) # AES加密后的密文 _send_text = MIMEText(_send_text, 'plain', 'utf-8') msg.attach(_send_text) # 加密文件 cipher_path = [] for path in self.path: cipher_path.append(Encryption().Encry_file(path)) # 加密图片文件 self.path[:] = [] for path in cipher_path: self.path.append(path) # 将加密后的附件路径添加至发送列表 # 添加附件 文件路径不能包含中文 if len(self.path) != 0: try: for file_path in self.path: print file_path file_part = MIMEApplication(open(file_path, 'rb').read()) file_part.add_header('Content-Disposition', 'attachment', filename=file_path) msg.attach(file_part) print "ADD SUCCESS" except Exception as e: print "ADD FILE ERROR ->", str(e) self.server.set_debuglevel(1) self.server = smtplib.SMTP(self.Smtp_Server, 25) # 与邮件服务器重新建立连接 self.server.login(self.user, self.passwd) # 重新登入 self.remain_windows = Tk() self.remain_windows.title("提示消息") try: self.server.sendmail(self.user, self.receiver, msg.as_string()) self.server.quit() remain_lable = Frame(self.remain_windows) Label(remain_lable, text="Send Success!").pack(fill="y", expand="yes") remain_lable.pack() self.remain_windows.mainloop() except Exception as e: print "Send Error - >", str(e) remain_lable = Frame(self.remain_windows) Label(remain_lable, text="Send Failed!").pack(fill="y", expand="yes") remain_lable.pack() self.remain_windows.mainloop() exit_button = Frame(self.remain_windows) Button(exit_button, text="Confirm", command=self.destory_windows).pack() exit_button.pack()
def main(): """Compile the list and send it out.""" # Parse command line arguments args = docopt.docopt(__doc__) # Set up logging log_level = logging.getLevelName(logging.WARNING) if args["--log-level"]: log_level = args["--log-level"] try: logging.basicConfig(format="%(asctime)-15s %(levelname)s %(message)s", level=log_level.upper()) except ValueError: logging.critical( f'"{log_level}" is not a valid logging level. Possible values are debug, info, warning, and error.' ) return 1 # Handle some command line arguments db_creds_file = args["--db-creds-file"] from_email = args["--from"] to_email = args["--to"] cc_email = args["--cc"] reply_email = args["--reply"] subject = args["--subject"] text_filename = args["--text"] html_filename = args["--html"] # Connect to the BOD 18-01 scan results database try: db = db_from_config(db_creds_file) except OSError: logging.critical( f"Database configuration file {db_creds_file} does not exist", exc_info=True) return 1 except yaml.YAMLError: logging.critical( f"Database configuration file {db_creds_file} does not contain valid YAML", exc_info=True, ) return 1 except KeyError: logging.critical( f"Database configuration file {db_creds_file} does not contain the expected keys", exc_info=True, ) return 1 except pymongo.errors.ConnectionError: logging.critical( f"Unable to connect to the database server in {db_creds_file}", exc_info=True, ) return 1 except pymongo.errors.InvalidName: logging.critical(f"The database in {db_creds_file} does not exist", exc_info=True) return 1 # Perform the query to retrieve all hosts that require # authentication via client certificates client_cert_hosts = query(db) # Build up the MIME message to be sent msg = MIMEMultipart("mixed") msg["From"] = from_email logging.debug(f"Message will be sent from: {from_email}") msg["To"] = to_email logging.debug(f"Message will be sent to: {to_email}") if cc_email is not None: msg["CC"] = cc_email logging.debug(f"Message will be sent as CC to: {cc_email}") if reply_email is not None: msg["Reply-To"] = reply_email logging.debug(f"Replies will be sent to: {reply_email}") msg["Subject"] = subject logging.debug(f"Message subject is: {subject}") # Construct and attach the text body body = MIMEMultipart("alternative") with open(text_filename, "r") as text: t = text.read() body.attach(MIMEText(t, "plain")) logging.debug(f"Message plain-text body is: {t}") with open(html_filename, "r") as html: h = html.read() html_part = MIMEText(h, "html") # See https://en.wikipedia.org/wiki/MIME#Content-Disposition html_part.add_header("Content-Disposition", "inline") body.attach(html_part) logging.debug(f"Message HTML body is: {h}") msg.attach(body) # Create CSV data from JSON data csv_output = io.StringIO() fieldnames = [ "Agency", "Base Domain", "Canonical URL", "Defaults To HTTPS", "Domain", "Domain Enforces HTTPS", "Domain Supports HTTPS", "Domain Uses Strong HSTS", "Downgrades HTTPS", "HSTS", "HSTS Base Domain Preloaded", "HSTS Entire Domain", "HSTS Header", "HSTS Max Age", "HSTS Preload Pending", "HSTS Preload Ready", "HSTS Preloaded", "HTTPS Bad Chain", "HTTPS Bad Hostname", "HTTPS Client Auth Required", "HTTPS Expired Cert", "HTTPS Full Connection", "HTTPS Live", "HTTPS Self Signed Cert", "Is Base Domain", "Live", "Redirect", "Redirect To", "Scan Date", "Strictly Forces HTTPS", "Unknown Error", "Valid HTTPS", ] writer = csv.DictWriter(csv_output, fieldnames=fieldnames) writer.writeheader() for result in client_cert_hosts: writer.writerow({ "Agency": result["agency"]["name"], "Base Domain": result["base_domain"], "Canonical URL": result["canonical_url"], "Defaults To HTTPS": result["defaults_https"], "Domain": result["domain"], "Domain Enforces HTTPS": result["domain_enforces_https"], "Domain Supports HTTPS": result["domain_supports_https"], "Domain Uses Strong HSTS": result["domain_uses_strong_hsts"], "Downgrades HTTPS": result["downgrades_https"], "HSTS": result["hsts"], "HSTS Base Domain Preloaded": result["hsts_base_domain_preloaded"], "HSTS Entire Domain": result["hsts_entire_domain"], "HSTS Header": result["hsts_header"], "HSTS Max Age": result["hsts_max_age"], "HSTS Preload Pending": result["hsts_preload_pending"], "HSTS Preload Ready": result["hsts_preload_ready"], "HSTS Preloaded": result["hsts_preloaded"], "HTTPS Bad Chain": result["https_bad_chain"], "HTTPS Bad Hostname": result["https_bad_hostname"], "HTTPS Client Auth Required": result["https_client_auth_required"], "HTTPS Expired Cert": result["https_expired_cert"], "HTTPS Full Connection": result["https_full_connection"], "HTTPS Live": result["https_live"], "HTTPS Self Signed Cert": result["https_self_signed_cert"], "Is Base Domain": result["is_base_domain"], "Live": result["live"], "Redirect": result["redirect"], "Redirect To": result["redirect_to"], "Scan Date": result["scan_date"].isoformat(), "Strictly Forces HTTPS": result["strictly_forces_https"], "Unknown Error": result["unknown_error"], "Valid HTTPS": result["valid_https"], }) # Attach (gzipped) CSV data csv_part = MIMEApplication( gzip.compress(csv_output.getvalue().encode("utf-8")), "gzip") csv_filename = "hosts_that_require_auth_via_client_certs.csv.gz" # See https://en.wikipedia.org/wiki/MIME#Content-Disposition csv_part.add_header("Content-Disposition", "attachment", filename=csv_filename) logging.debug(f"Message will include file {csv_filename} as attachment") msg.attach(csv_part) # Send the email ses_client = boto3.client("ses") response = ses_client.send_raw_email(RawMessage={"Data": msg.as_string()}) # Check for errors status_code = response["ResponseMetadata"]["HTTPStatusCode"] if status_code != 200: logging.error( f"Unable to send message. Response from boto3 is: {response}") return 2 # Stop logging and clean up logging.shutdown()
def send(doc_id): logging.info('Received %s' % doc_id) """given the doc_id, send email """ #couchdb settings couch_server = couchdb.Server(settings.COUCH_DSN) db = couch_server['mailbox'] doc = db.get(doc_id) if doc == None: raise Exception('Failed to Send Invoice', '%s not found' % doc_id) msg = MIMEMultipart() #text part if doc.has_key('text'): if doc['text'] != None: text_message = string.strip(doc['text']) if text_message != '': part1 = MIMEText('%s' % text_message, 'plain', 'utf-8') part1.add_header('Content-Disposition', 'inline') msg.attach(part1) if doc.has_key('html'): if doc['html'] != None: html_message = string.strip(doc['html']) if html_message != '': part2 = MIMEText('%s' % html_message, 'html', 'UTF-8') part2.add_header('Content-Disposition', 'inline') msg.attach(part2) subject = doc['subject'] if settings.DEBUG == True: #subject = 'TEST %s' % subject subject = 'TEST Recipients : %s . %s' % (string.join(doc['to'], ','), subject) msg['Subject'] = subject if doc.has_key('from'): msg['From'] = doc['from'] else: msg['From'] = "*****@*****.**" try: msg['To'] = string.join(doc['to'], ',') except: msg['To'] = '*****@*****.**' try: if doc.has_key('cc'): if doc['cc'] != None: msg['Cc'] = string.join(doc['cc'], ',') except: pass #attachments try: if doc.has_key('_attachments'): for attachment in doc['_attachments']: f = db.get_attachment(doc, attachment) data = f.read() file_attachment = MIMEApplication(data) file_attachment.add_header('Content-Disposition', 'attachment', filename=attachment) msg.attach(file_attachment) except: pass #collect recipients recipients = [] if settings.DEBUG: recipients.append('*****@*****.**') else: for email in doc['to']: recipients.append(email) try: if doc.has_key('cc'): if doc['cc'] != None: for email in doc['cc']: recipients.append(email) except: pass if doc.has_key('bcc'): if doc['bcc'] != None: for email in doc['bcc']: recipients.append(email) #add reply_to field reply_to = doc.get('reply_to') if reply_to not in (None, ''): msg['Reply-To'] = reply_to sender = doc.get('sender') if sender not in (None, ''): msg['Sender'] = sender #add In-Reply-To and References headers in_reply_to = doc.get('In-Reply-To') if in_reply_to != None: msg['In-Reply-To'] = in_reply_to references = doc.get('References') if references != None: msg['References'] = references mailer = "" is_invoice = False if doc.has_key("is_invoice"): if subject == None or subject == "": subject = "Remotestaff Tax Invoice # %s" % doc["order_id"] #Injected By Josef Balisalisa START import sendgrid import os from sendgrid.helpers.mail import * from pymongo import MongoClient import re import base64 import pprint is_invoice = False logging.info("Evaluating if email is invoice") try: if doc.has_key('is_invoice'): logging.info("Sending as Invoice via Send Grid %s " % doc_id) mailer = "Send Grid" sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY) debugging_env = "prod" if settings.DEBUG: debugging_env = "development" data = { "personalizations": [{ "to": [], "subject": subject }], "from": { "email": doc["from"] }, "content": [], "custom_args": { "accounts_order_id": doc["order_id"], "debugging_env": debugging_env, "couch_id": doc_id }, } data_to_save = {} data_to_save["from"] = doc["from"] if doc.has_key('html'): if doc['html'] != None: html_message = string.strip(doc['html']) data["content"].append({ "type": "text/html", "value": html_message }) data_to_save["html_content"] = html_message if doc.has_key('text'): if doc['text'] != None: text_message = string.strip(doc['text']) data["content"].append({ "type": "text/plain", "value": text_message }) data_to_save["text_content"] = text_message data_to_save["to"] = [] data_to_save["cc"] = [] data_to_save["bcc"] = [] if settings.DEBUG: # data["personalizations"][0]["to"].append({"email":"*****@*****.**"}) # data_to_save["to"].append("*****@*****.**") logging.info("SendGrid TEST") # data["mail_settings"] = {} # data["mail_settings"]["sandbox_mode"] = {} # data["mail_settings"]["sandbox_mode"]["enable"] = True # logging.info("SendGrid Sandbox details: %s " % data["mail_settings"]) emails_appended = [] for email in recipients: if email.lower() not in emails_appended: data["personalizations"][0]["to"].append( {"email": email}) emails_appended.append(email.lower()) data_to_save["to"].append(email) logging.info("sending to %s " % data["personalizations"][0]["to"]) else: logging.info("SendGrid Data Prod") #to #cc #bcc emails_appended = [] data["personalizations"][0]["bcc"] = [] for email in recipients: try: if email.lower() != "*****@*****.**": if email.lower() not in emails_appended: data["personalizations"][0]["to"].append( {"email": email}) emails_appended.append(email.lower()) data_to_save["to"].append(email) except Exception, e: logging.info("Error appending recepients %s " % str(e)) pass try: if doc.has_key('cc'): if doc['cc'] != None: data["personalizations"][0]["cc"] = [] for email in doc['cc']: if email.lower() not in emails_appended: data["personalizations"][0]["cc"].append( {"email": email}) emails_appended.append(email.lower()) data_to_save["cc"].append(email) except Exception, e: logging.info("Error adding cc email %s " % str(e)) pass try: if doc.has_key('bcc'): if doc['bcc'] != None: data["personalizations"][0]["bcc"] = [] for email in doc['bcc']: if email.lower() not in emails_appended: data["personalizations"][0]["bcc"].append( {"email": email}) data_to_save["bcc"].append(email) emails_appended.append(email.lower()) except Exception, e: logging.info("Error appending bcc %s " % str(e)) pass devs_bcc_email = "*****@*****.**" if devs_bcc_email.lower() not in emails_appended: data["personalizations"][0]["bcc"].append( {"email": devs_bcc_email})
#여러 MIME을 넣기위한 MIMEMultipart 객체 생성 msg = MIMEMultipart() # 본문추가 text = 'python Email Test2' contentPart = MIMEText(text) msg.attach(contentPart) # 파일추가 etcFileName = 'smtpEmail.png' with open(etcFileName, 'rb') as etcFD: etcPart = MIMEApplication(etcFD.read()) # 첨부파일 정보를 헤더로 추가 etcPart.add_header('Content-Disposition', 'attachment', filename=etcFileName) msg.attach(etcPart) msg['Subject'] = 'test2' msg['From'] = sendEmail msg['To'] = recvEmail print(msg.as_string()) s = smtplib.SMTP(smtpName, smtPort) # 메일 서버 연결(s가 구글서버와 통신하는 하는 통로) s.starttls() # TLS 보안처리 s.login(sendEmail, password) # 계정 로그인 s.sendmail(sendEmail, recvEmail, msg.as_string()) # 메일 전송, 문자열 반환 s.close()
def SendEamil(request): #查询github监控数据 RequestLogRecord(request, request_api="send_fishing_mail") if request.method == "POST": try: Token = json.loads(request.body)["token"] MailMessage = json.loads(request.body)["mail_message"] #文本内容 Attachment = json.loads(request.body)["attachment"] #附件列表 MailTitle = json.loads(request.body)["mail_title"] # 邮件标题 Sender = json.loads(request.body)["sender"] # 发送人姓名 GoalMailbox = json.loads(request.body)["goal_mailbox"] # 目标邮箱 Uid = UserInfo().QueryUidWithToken(Token) # 如果登录成功后就来查询UID if Uid != None: # 查到了UID UserOperationLogRecord(request, request_api="send_fishing_mail", uid=Uid) # 查询到了在计入 # 邮件内容 for Target in GoalMailbox: #像多个目标发送 try: EmailBox = MIMEMultipart() # 创建容器 EmailBox[ 'From'] = Sender + "<" + mail_user + ">" # 发送人 EmailBox['To'] = Target # 发给谁 EmailBox['Subject'] = Header(MailTitle, 'utf-8') # 标题 # 发送附件 MailAttachmentFilePath = GetMailAttachmentFilePath( ).Result() for i in Attachment: AttachmentData = MIMEApplication( open(MailAttachmentFilePath + i, 'rb').read()) AttachmentData.add_header('Content-Disposition', 'attachment', filename=i) EmailBox.attach(AttachmentData) # 消息正文 TextMessage = MIMEMultipart('alternative') EmailBox.attach(TextMessage) TextMessage.attach( MIMEText(MailMessage, 'html', 'utf-8')) # # 指定图片为当前目录 # MailImageFilePath = GetMailImageFilePath().Result() # file = open(image_file, "rb") # img_data = file.read() # file.close() # img = MIMEImage(img_data) # img.add_header('Content-ID', 'dns_config') # EmailBox.attach(img) SMTP = smtplib.SMTP() SMTP.connect(mail_host, 25) # 25 为 SMTP 端口号 SMTP.login(mail_user, mail_pass) SMTP.sendmail(mail_user, Target, EmailBox.as_string()) print("成功" + Target) SMTP.quit() SMTP.close() except Exception as e: print("失败" + Target) #到时候写数据库 return JsonResponse({ 'message': "发送失败!!", 'code': 503, }) return JsonResponse({ 'message': "发送成功~", 'code': 200, }) else: return JsonResponse({ 'message': "小宝贝这是非法查询哦(๑•̀ㅂ•́)و✧", 'code': 403, }) except Exception as e: ErrorLog().Write("Web_Mail_SendEamil_SendEamil(def)", e) else: return JsonResponse({ 'message': '请使用Post请求', 'code': 500, })
password = "" # 邮件设置 msg = MIMEMultipart() msg['Subject'] = asubject msg['to'] = areceiver msg['Cc'] = acc msg['from'] = "" # 邮件正文 body = "你好,这是一份测试邮件" msg.attach(MIMEText(body, 'plain', 'utf-8')) # 添加附件 xlsxpart = MIMEApplication(open('./report.csv', 'rb').read()) xlsxpart.add_header('Content-Disposition', 'attachment', filename='report.csv') msg.attach(xlsxpart) # 设置邮箱服务器地址及端口 smtp_server = "smtp.163.com" server = smtplib.SMTP(smtp_server, 25) # 打印日志 server.set_debuglevel(1) # 登录邮箱 server.login(from_addr, password) # 发送邮件 server.sendmail(from_addr, areceiver.split(',') + acc.split(','), msg.as_string())
mail_title = 'Python办公自动化的邮件' #邮件标题 mail_content = '你好,这是使用Python自动发送的邮件' #邮件的正文内容 mail_content1 = "你好,<p>这是使用Python自动发送的邮件</p><p><a href='http://python.cn'> python</p> " #邮件的正文内容 #构造邮件主题 msg = MIMEMultipart() msg['Subject'] = Header(mail_title, 'utf-8') msg['From'] = sender_sina_mail msg['To'] = Header('测试邮箱', 'utf-8') msg.attach(MIMEText(mail_content, 'plain', 'utf-8')) #plain是无格式发送,html是网页格式发送内容 msg.attach(MIMEText(mail_content, 'html', 'utf-8')) #发送带格式的网页 att = MIMEApplication(open('D:/123.doc', 'rb').read()) #添加附件 att.add_header('Content-Disposition', 'attachment', filename='test.doc') #附件重命名 msg.attach(att) #给邮件添加附件 #登录邮箱发送 try: smtp = SMTP_SSL(host_server) smtp.set_debuglevel(1) smtp.ehlo(host_server) smtp.login(sender_sina, pwd) smtp.sendmail(sender_sina_mail, receiver, msg.as_string()) smtp.quit() print('邮件发送成功') except smtplib.SMTPException: print('邮件发送失败')
server = smtplib.SMTP('smtp.gmail.com: 587') server.starttls() server.login(msg['From'], password) file_res = input('Would you like to add some files? [Y/n]') if file_res.lower() == 'y': count_files = int(input('How much files do you want to add? ')) files_paths = [input('Enter file path: ') for iter in range(count_files)] for path in files_paths: msg.attach(MIMEText(message, 'plain')) file = MIMEApplication(open(path, 'rb').read()) file.add_header('Content-Depisotion', 'attachment', filename=path) msg.attach(file) pic_res = input('Would you like to add some pictures? [Y/n] ') if pic_res == 'y': count_pic = int(input('How much pictures do you want to add? ')) pics_paths = [input('Enter pic path: ') for iter in range(count_pic)] for path in pics_paths: img = MIMEImage(open(path, 'rb').read(), _subtype="jpg") img.add_header('Content-Disposition', 'attachment', filename='') msg.attach(img) count_messages = int(input('How much messages would you like to send? '))
Titulo = 'Envio documento para kindler' Texto = 'Envio documento para Kindler' #hacia donde el correo mensaje = MIMEMultipart() mensaje['Subject'] = Titulo mensaje['From'] = De mensaje['To'] = Para #Agrega texto cuerpo = MIMEText(Texto) mensaje.attach(cuerpo) #Agrega PDF archivo = 'DeepC_Scandev_Mar2013.pdf' fp = open(archivo, 'rb') att = MIMEApplication(fp.read(), _subtype="pdf") fp.close() att.add_header('Content-Disposition', 'attachment; filename=%s' % archivo) mensaje.attach(att) try: smtpObj = smtplib.SMTP(servidor, puerto) smtpObj.ehlo() smtpObj.starttls() smtpObj.ehlo smtpObj.login(De, 'x15281565') smtpObj.sendmail(De, Para, mensaje.as_string()) print "El mensaje se envio de forma exitosa" except SMTPException: print "Existe un problema para enviar el mensaje"
# <p>Test # </p> # </body> # </html> # """ part2 = MIMEText(html, 'html', 'utf-8') if args.attachment is not None: text_msg.attach(part2) else: msg.attach(part2) if args.attachment is not None: msg.attach(text_msg) with open(args.attachment, 'rb') as file: attachment = MIMEApplication(file.read(), 'octet-stream') attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file.name)) msg.attach(attachment) # print msg.as_string().encode('ascii') print "sending" s = smtplib.SMTP('ssl0.ovh.net', 587) s.set_debuglevel(1) s.login(user, password) # sendmail function takes 3 arguments: sender's address, recipient's address # and message to send - here it is sent as one string. s.sendmail(sender, receiver, msg.as_string().encode('ascii')) s.quit()
message = MIMEMultipart() #设置邮件头 message['Subject'] = Header('公众号[桔子code]:邮箱看家护院', 'utf-8').encode() name, addr = parseaddr('Jerry <%s>' % from_addr) message['From'] = formataddr((Header(name, 'utf-8').encode(), addr)) name, addr = parseaddr('Tom <%s>' % to_addr) message['To'] = formataddr((Header(name, 'utf-8').encode(), addr)) #读取图片 image_data = None with open('capture.jpg', 'rb') as pf: image_data = pf.read() #生成图片附件: imgpart = MIMEApplication(image_data) imgpart.add_header('Content-Disposition', 'attachment', filename='capture.jpg') message.attach(imgpart) #生成图片正文 img = MIMEImage(image_data) img.add_header('Content-ID', 'capture-1') #对应<img> src属性 message.attach(img) #生成邮件正文 mail_cont="""<table > <tr><td> 关注微信公众号: [桔子code],及时接收更好玩的Python</td></tr> <tr><td><img src="cid:capture-1"></td> </tr> </table>""" # <img> src属性通过Content-ID引用 text = MIMEText(mail_cont, "html", "utf-8") message.attach(text)
from email.mime.application import MIMEApplication #传附件 #总的邮件内容,分为不同的模块 msg_total=MIMEMultipart() msg_total['Subject']="hello" #正文模块 msg_raw="""<p style="color:red">你好</p> """ msg=MIMEText(msg_raw,'html') msg_total.attach(msg) #附件模块 file=MIMEApplication(open('demo.txt','rb').read()) #添加附件的头信息 file.add_header('Content-Dispostion','attachment',filename='demo.txt') #附件模块添加到总的里面 msg_total.attach(file) with smtplib.SMTP_SSL('smtp.163.com',465) as server: server.login(emailname,emailpwd) server.starttls(context=context) #加密 # msg = '''\\ # From: chen # Subject: testin' # # This is a test ''' server.sendmail(emailname,'*****@*****.**',msg_total.as_string())
#lists clist = 'Wipro', 'GHD', 'Disney' #list of companies nlist = 'Sidharth', 'Eric', 'Thomas' #list of company representatives elist = '*****@*****.**', '*****@*****.**', '*****@*****.**' #list of email ids of representatives #Iterate the forloop to send email to each company representative. for i in range(0, len(elist)): msg = MIMEMultipart() msg['From'] = 'Sidharth Jasra <*****@*****.**>' msg['To'] = '%s <' % nlist[i] + elist[i] + '>' msg['Subject'] = 'Thank you for attending our conference and sharing your views on work life at %s' % clist[ i] #email file attachment filename = 'Gift_Card.pdf' fp = open(filename, 'rb') att = MIMEApplication(fp.read(), _subtype="pdf") att.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(att) #Email template message = 'Hi %s,\n\nHope you are doing well!\n\n\ It is really nice to meet you at the conference last evening.\ The thoughts you have shared with audience about the work culture at %s was really helpful for me.\ Thank you so much for valuable insights about the company.\ I am attaching a gift card for you.\n\n\n- Sidharth' % (nlist[i], clist[i]) msg.attach(MIMEText(message)) smtpObj.sendmail('*****@*****.**', elist[i], msg.as_string()) smtpObj.quit()
def apply_mtom(headers, envelope, params, paramvals): """Apply MTOM to a SOAP envelope, separating attachments into a MIME multipart message. Returns a tuple of length 2 with dictionary of headers and string of body that can be sent with HTTPConnection References: XOP http://www.w3.org/TR/xop10/ MTOM http://www.w3.org/TR/soap12-mtom/ http://www.w3.org/Submission/soap11mtom10/ :param headers Headers dictionary of the SOAP message that would originally be sent. :param envelope Iterable containing SOAP envelope string that would have originally been sent. :param params params attribute from the Message object used for the SOAP :param paramvals values of the params, passed to Message.to_parent """ # grab the XML element of the message in the SOAP body envelope = ''.join(envelope) soaptree = etree.fromstring(envelope) soapbody = soaptree.find("{%s}Body" % _ns_soap_env) message = None for child in list(soapbody): if child.tag == ("{%s}Fault" % _ns_soap_env): return headers, envelope else: message = child break # Get additional parameters from original Content-Type ctarray = [] for n, v in headers.items(): if n.lower() == 'content-type': ctarray = v.split(';') break roottype = ctarray[0].strip() rootparams = {} for ctparam in ctarray[1:]: n, v = ctparam.strip().split('=') rootparams[n] = v.strip("\"'") # Set up initial MIME parts. mtompkg = MIMEMultipart('related', boundary='?//<><>spyne_MIME_boundary<>') rootpkg = MIMEApplication(envelope, 'xop+xml', encode_7or8bit) # Set up multipart headers. del mtompkg['mime-version'] mtompkg.set_param('start-info', roottype) mtompkg.set_param('start', '<spyneEnvelope>') if 'SOAPAction' in headers: mtompkg.add_header('SOAPAction', headers.get('SOAPAction')) # Set up root SOAP part headers. del rootpkg['mime-version'] rootpkg.add_header('Content-ID', '<spyneEnvelope>') for n, v in rootparams.items(): rootpkg.set_param(n, v) rootpkg.set_param('type', roottype) mtompkg.attach(rootpkg) # Extract attachments from SOAP envelope. for i in range(len(params)): name, typ = params[i] if typ in (ByteArray, Attachment): id = "spyneAttachment_%s" % (len(mtompkg.get_payload()), ) param = message[i] param.text = "" incl = etree.SubElement(param, "{%s}Include" % _ns_xop) incl.attrib["href"] = "cid:%s" % id if paramvals[i].fileName and not paramvals[i].data: paramvals[i].load_from_file() if type == Attachment: data = paramvals[i].data else: data = ''.join(paramvals[i]) attachment = MIMEApplication(data, _encoder=encode_7or8bit) del attachment['mime-version'] attachment.add_header('Content-ID', '<%s>' % (id, )) mtompkg.attach(attachment) # Update SOAP envelope. rootpkg.set_payload(etree.tostring(soaptree)) # extract body string from MIMEMultipart message bound = '--%s' % (mtompkg.get_boundary(), ) marray = mtompkg.as_string().split(bound) mtombody = bound mtombody += bound.join(marray[1:]) # set Content-Length mtompkg.add_header("Content-Length", str(len(mtombody))) # extract dictionary of headers from MIMEMultipart message mtomheaders = {} for name, value in mtompkg.items(): mtomheaders[name] = value if len(mtompkg.get_payload()) <= 1: return headers, envelope return mtomheaders, [mtombody]
def addAttchment(self, filename=""): content = self._getContent(filename=filename, mode='rb') attachment = MIMEApplication(content) attachment.add_header("Content-Disposition", "attachment", filename=filename) self.message.attach(attachment)
def apply_mtom(headers, envelope, params, paramvals): ''' Apply MTOM to a SOAP envelope, separating attachments into a MIME multipart message. References: XOP http://www.w3.org/TR/xop10/ MTOM http://www.w3.org/TR/soap12-mtom/ http://www.w3.org/Submission/soap11mtom10/ @param headers Headers dictionary of the SOAP message that would originally be sent. @param envelope SOAP envelope string that would have originally been sent. @param params params attribute from the Message object used for the SOAP @param paramvals values of the params, passed to Message.to_xml @return tuple of length 2 with dictionary of headers and string of body that can be sent with HTTPConnection ''' # grab the XML element of the message in the SOAP body soapmsg = StringIO(envelope) soaptree = ElementTree.parse(soapmsg) soapns = soaptree.getroot().tag.split('}')[0].strip('{') soapbody = soaptree.getroot().find("{%s}Body" % soapns) message = None for child in list(soapbody): if child.tag != "%sFault" % (soapns, ): message = child break # Get additional parameters from original Content-Type ctarray = [] for n, v in headers.items(): if n.lower() == 'content-type': ctarray = v.split(';') break roottype = ctarray[0].strip() rootparams = {} for ctparam in ctarray[1:]: n, v = ctparam.strip().split('=') rootparams[n] = v.strip("\"'") # Set up initial MIME parts mtompkg = MIMEMultipart('related', boundary='?//<><>soaplib_MIME_boundary<>') rootpkg = None try: rootpkg = MIMEApplication(envelope, 'xop+xml', encode_7or8bit) except NameError: rootpkg = MIMENonMultipart("application", "xop+xml") rootpkg.set_payload(envelope) encode_7or8bit(rootpkg) # Set up multipart headers. del (mtompkg['mime-version']) mtompkg.set_param('start-info', roottype) mtompkg.set_param('start', '<soaplibEnvelope>') if 'SOAPAction' in headers: mtompkg.add_header('SOAPAction', headers.get('SOAPAction')) # Set up root SOAP part headers. del (rootpkg['mime-version']) rootpkg.add_header('Content-ID', '<soaplibEnvelope>') for n, v in rootparams.items(): rootpkg.set_param(n, v) rootpkg.set_param('type', roottype) mtompkg.attach(rootpkg) # Extract attachments from SOAP envelope. for i in range(len(params)): name, typ = params[i] if typ == Attachment: id = "soaplibAttachment_%s" % (len(mtompkg.get_payload()), ) param = message[i] param.text = "" incl = create_xml_subelement( param, "{http://www.w3.org/2004/08/xop/include}Include") incl.attrib["href"] = "cid:%s" % id if paramvals[i].fileName and not paramvals[i].data: paramvals[i].load_from_file() data = paramvals[i].data attachment = None try: attachment = MIMEApplication(data, _encoder=encode_7or8bit) except NameError: attachment = MIMENonMultipart("application", "octet-stream") attachment.set_payload(data) encode_7or8bit(attachment) del (attachment['mime-version']) attachment.add_header('Content-ID', '<%s>' % (id, )) mtompkg.attach(attachment) # Update SOAP envelope. soapmsg.close() soapmsg = StringIO() soaptree.write(soapmsg) rootpkg.set_payload(soapmsg.getvalue()) soapmsg.close() # extract body string from MIMEMultipart message bound = '--%s' % (mtompkg.get_boundary(), ) marray = mtompkg.as_string().split(bound) mtombody = bound mtombody += bound.join(marray[1:]) # set Content-Length mtompkg.add_header("Content-Length", str(len(mtombody))) # extract dictionary of headers from MIMEMultipart message mtomheaders = {} for name, value in mtompkg.items(): mtomheaders[name] = value if len(mtompkg.get_payload()) <= 1: return (headers, envelope) return (mtomheaders, mtombody)
content += "祝好 \n" content += "王五" message = MIMEMultipart() message['Subject'] = '期末考试成绩' message['From'] = sender message['To'] = worksheet.cell(row=i, column=3).value message.attach(MIMEText(content, 'plain', 'utf-8')) if (doGenerateIndividualFiles): excelFile = 'IndividualFiles/%s.xlsx' % worksheet.cell(row=i, column=1).value excelPart = MIMEApplication(open(excelFile, 'rb').read()) excelPart.add_header('Content-Disposition', 'attachment', filename='作业成绩.xlsx') message.attach(excelPart) receiver = message['To'] print("send to : ", message['To']) try: smtpObj.sendmail(sender, receiver, message.as_string()) except: print("Error : Failed Sending Mail to ", receiver) FailedAddress.append(receiver) else: SuccessCount += 1 print()
def lambda_handler(event, context): s3 = boto3.client('s3') b = ('cfaitinnovnp.autoinvoice.raw-email') emailName = event['Records'][0]['s3']['object']['key'] resource = s3.get_object(Bucket=b, Key=emailName) text = (resource['Body'].read().decode("utf-8")) s3.delete_object(Bucket=b, Key=emailName) ##the above pulls the text body from an email trigger and puts it into var text regex = r"(?s)(Content-Transfer-Encoding: base64)([^-]*)" client = boto3.client('ses', region_name='us-east-1') emailTo = (re.search(r"Return-Path: <(.*)>", text).group(1)) emailFrom = '*****@*****.**' region = 'us-east-1' try: result = re.search(regex, text) pdfBlock = (result.group(2)) bytes = b64decode(pdfBlock) if bytes[0:4] != b'%PDF': raise ValueError('Missing the PDF file signature') # Write the PDF contents to a local file pdfName = re.search(r"Content-Type: application/pdf; name=(.*)", text).group(1) pdfName = pdfName[1:(len(pdfName) - 1)] f = open('/tmp/' + pdfName, 'wb') f.write(bytes) f.close() msg = MIMEMultipart('mixed') # Add subject, from and to lines. msg['Subject'] = "PDF Test Back" msg['From'] = emailFrom msg['To'] = emailTo BODY_TEXT = "Hello,\r\nPlease see the attached file for the soon-to-be routed PDF." # The HTML body of the email. BODY_HTML = """\ <html> <head></head> <body> <h1>Hello!</h1> <p>Please see the attached file for the soon-to-be routed PDF.</p> </body> </html> """ CHARSET = "UTF-8" msg_body = MIMEMultipart('alternative') ATTACHMENT = '/tmp/' + pdfName # Encode the text and HTML content and set the character encoding. This step is # necessary if you're sending a message with characters outside the ASCII range. textpart = MIMEText(BODY_TEXT.encode(CHARSET), 'plain', CHARSET) htmlpart = MIMEText(BODY_HTML.encode(CHARSET), 'html', CHARSET) # Add the text and HTML parts to the child container. msg_body.attach(textpart) msg_body.attach(htmlpart) # Define the attachment part and encode it using MIMEApplication. att = MIMEApplication(open(ATTACHMENT, 'rb').read()) att.add_header('Content-Disposition', 'attachment', filename=os.path.basename(ATTACHMENT)) # Attach the multipart/alternative child container to the multipart/mixed # parent container. msg.attach(msg_body) # Add the attachment to the parent container. msg.attach(att) try: #Provide the contents of the email. response = client.send_raw_email(Source=emailFrom, Destinations=[emailTo], RawMessage={ 'Data': msg.as_string(), }) # Display an error if something goes wrong. except ClientError as e: print(e.response['Error']['Message']) except: ##sends the bounce back no pdf email subject = "[Invoice Automation] No Invoice Attached" body_text = ( "Hello,\n There was no invoice attached to the last email " "sent to [email protected]. Please resend with a PDF attachment." ) html_text = """<html> <head></head> <body> <h1>Hello,</h1> <p>There was no invoice attached to the last email sent to [email protected]. Please resend with a PDF attachment.</p> </body> </html>""" charset = "UTF-8" try: response = client.send_email(Destination={ 'ToAddresses': [ emailTo, ], }, Message={ 'Body': { 'Html': { 'Charset': charset, 'Data': html_text, }, 'Text': { 'Charset': charset, 'Data': body_text, }, }, 'Subject': { 'Charset': charset, 'Data': subject, }, }, Source=emailFrom) # Display an error if something goes wrong. except ClientError as e: print(e.response['Error']['Message']) return
def handle_attachment(line, target, message): """ Mac versions put "Attachment converted", Windows (Lite) has "Attachment Converted". Next comes a system-dependent path to the attachment binary. On mac version, separated by colons, starts with volume, but omits path elements between: Eudora Folder:Attachments Folder. Windows versions have a full DOS path name to the binary (Lite version uses 8-char filenames) This replaces that filepath with a file URI to the file in the attachments_dirs directories. This has no direct effect in Kmail, but sometimes Pine can open the file (so long as there aren't any spaces in the filepath). At least it makes more sense than leaving the old filepath. """ global attachments_listed, attachments_found, attachments_missing, attachments_dirs global paths_found, paths_missing global missing_attachments, found_attachments global mac_mismatches attachments_listed = attachments_listed + 1 # Mac 1.3.1 has e.g. (Type: 'PDF ' Creator: 'CARO') # Mac 3.1 has e.g (PDF /CARO) (00000645) if re_quoted_attachment.match(line): attachment_desc = re_quoted_attachment.sub('\\1', line) elif re_attachment.match(line): attachment_desc = re_attachment.sub('\\1', line) else: # If we're dealing with attachments recorded by the # X-Attachments header, line will be a single, naked # attachment desc, with no Attachment Converted # surroundings attachment_desc = line if attachment_desc.find('"') != -1: print "**>>**", attachment_desc attachment_desc = strip_linesep(attachment_desc) # some of John's attachment names have an odd OutboundG4: # prefix which is not present in the filenames on disk.. if attachment_desc.find('OutboundG4:') != -1: attachment_desc = attachment_desc.replace('OutboundG4:', '') name = '' # if has :\, must be windows etc = '' if re_dos_path_beginning.match(attachment_desc): desc_list = attachment_desc.split("\\") # DOS backslashes name = desc_list.pop().strip() # pop off last portion of name orig_path = "/".join(desc_list) if name[-1] == '"': name = name[:-1] elif re_mac_info.match(line): name = re_mac_info.sub('\\1', line) etc = re_mac_info.sub('\\2', line).strip() dlist = name.split(":") # Mac path delim name = dlist.pop().strip() # pop off last portion of name orig_path = "/".join(dlist) else: # EudoraLog.log.warn( "FAILED to convert attachment: \'" # + attachment_desc + "\'" ) name = attachment_desc orig_path = attachment_desc if len(name) <= 0: return filename = None for adir in attachments_dirs: if not filename or not os.path.exists(filename): filename = os.path.join(target, adir, name) if not os.path.isabs(target): filename = os.path.join(os.environ['HOME'], filename) # Trim NULL bytes from filenames (found in old Eudora 2.x mailboxes) filename = filename.replace(b'\x00', '') if not os.path.exists(filename): if name.startswith('OutboundG4:'): name = name[11:] print "**** Hey, name is now %s" % (name, ) filename = os.path.join(target, attachments_dir, name) # our user has attachments that have / characters in # the file name, but when they got copied over to # unix, the / chars were taken out, if it would help. if not os.path.exists(filename): if name.find('/') != -1: name = name.replace('/', '') filename = os.path.join(target, adir, name) # our user also has attachments that have _ characters # in the file name where the file on disk has spaces. # translate that as well, if it would help. if not os.path.exists(filename): if name.find('_') != -1: name = name.replace('_', ' ') filename = os.path.join(target, adir, name) # our user actually also has attachments that have # space characters in the file name where the file on # disk has underscores. if we didn't find the match # after our last transform, try the rever if not os.path.exists(filename): if name.find(' ') != -1: name = name.replace(' ', '_') filename = os.path.join(target, adir, name) # in our user's attachments, we have some files named # akin to 'filename.ppt 1' and so forth. we're going # to trim anything after the first whitespace # character after the first . in the filename cleaner_match = re_filename_cleaner.match(filename) if cleaner_match: filename = cleaner_match.group(1) # Trim any NULL bytes we might have pulled in filename = filename.replace(b'\x00', '') mimeinfo = mimetypes.guess_type(filename) if not os.path.exists(filename): cleaner_match = re_filename_cleaner.match(filename.replace('_', ' ')) if cleaner_match and os.path.exists(cleaner_match.group(1)): filename = cleaner_match.group(1) if not mimeinfo[0]: (mimetype, mimesubtype) = ('application', 'octet-stream') else: (mimetype, mimesubtype) = mimeinfo[0].split('/') if os.path.isfile(filename): fp = open(filename, 'rb') try: if mimetype == 'application' or mimetype == 'video': msg = MIMEApplication(fp.read(), _subtype=mimesubtype) elif mimetype == 'image': msg = MIMEImage(fp.read(), _subtype=mimesubtype) elif mimetype == 'text': msg = MIMEText(fp.read(), _subtype=mimesubtype) elif mimetype == 'audio': msg = MIMEAudio(fp.read(), _subtype=mimesubtype) else: EudoraLog.log.error( "Unrecognized mime type '%s' while processing attachment '%s'" % (mimeinfo[0], filename)) return finally: fp.close() msg.add_header('Content-Disposition', 'attachment', filename=name) message.attach(msg) attachments_found = attachments_found + 1 # EudoraLog.log.warn(" SUCCEEDED finding attachment: \'" + attachment_desc + "\', name = \'" + name + "\'") if orig_path in paths_found: paths_found[orig_path] = paths_found[orig_path] + 1 else: paths_found[orig_path] = 1 if not EudoraLog.log.mbx_name() in found_attachments: found_attachments[EudoraLog.log.mbx_name()] = [] found_attachments[EudoraLog.log.mbx_name()].append( (attachment_desc, filename)) else: attachments_missing = attachments_missing + 1 if not EudoraLog.log.mbx_name() in missing_attachments: missing_attachments[EudoraLog.log.mbx_name()] = [] missing_attachments[EudoraLog.log.mbx_name()].append(attachment_desc) # EudoraLog.log.warn(" FAILED to find attachment: \'" + attachment_desc + "\'" ) if re_mangled_mac.search(filename): print "Mac pattern: %s" % (filename, ) mac_mismatches.append(filename) if orig_path in paths_missing: paths_missing[orig_path] = paths_missing[orig_path] + 1 else: paths_missing[orig_path] = 1
def send_success_email(job_config, emailaddr_from="*****@*****.**"): """ Send an email alert with an attachment. Modified substantially from: http://blog.vero4ka.info/blog/2016/10/26/how-to-send-an-email-with-attachment-via-amazon-ses-in-python/ https://gist.github.com/yosemitebandit/2883593 :param job_config: MorfJobConfig object. :param emailaddr_from: address to send email from (string). :return: """ aws_access_key_id = job_config.aws_access_key_id aws_secret_access_key = job_config.aws_secret_access_key proc_data_bucket = job_config.proc_data_bucket job_id = job_config.job_id user_id = job_config.user_id emailaddr_to = job_config.email_to status = job_config.status job_config.update_mode( "test" ) # need to set mode so that correct key path is used to fetch results results_file_name = "morf-results.csv" s3 = boto3.client("s3", aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key) # fetch model evaluation results attachment_basename = generate_archive_filename(job_config, mode="evaluate", extension="csv") key = make_s3_key_path(job_config, filename=attachment_basename) attachment_filepath = download_from_s3(proc_data_bucket, key, s3) with open(attachment_filepath) as f: data = f.read() output = io.StringIO(data) # Build an email subject_text = construct_message_subject(job_config) msg = MIMEMultipart() msg["Subject"] = subject_text msg["From"] = emailaddr_from msg["To"] = emailaddr_to # What a recipient sees if they don't use an email reader msg.preamble = "Multipart message.\n" # the body body_text = construct_message_body(job_config) body = MIMEText(body_text) msg.attach(body) # The attachment part = MIMEApplication(output.getvalue()) part.add_header("Content-Disposition", "attachment", filename=results_file_name) part.add_header("Content-Type", "application/vnd.ms-excel; charset=UTF-8") msg.attach(part) # Connect to Amazon SES ses = boto3.client( "ses", region_name="us-east-1", aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, ) # And finally, send the email try: ses.send_raw_email(Source=emailaddr_from, Destinations=[emailaddr_to, emailaddr_from], RawMessage={ 'Data': msg.as_string(), }) print("[INFO] email notification sent emailaddr_to {}".format( emailaddr_to)) except Exception as e: print("[WARNING] error sending email to {}: {}".format( emailaddr_to, e)) return
def mail_send(mail_body, mail_group): """ :param mail_body: :param mail_group: :return: """ # 从mail_body 创建邮件主体 mb_json = json.loads(mail_body) message = MIMEMultipart() # 添加邮件的文本内容 text = mb_json['data']['text'] textApart = MIMEText(text, 'html', 'utf-8') message.attach(textApart) # 是否有附件 for file in mb_json['file']: # 创建附件 fileApart = MIMEApplication(open(file, 'rb').read()) fileApart.add_header('Content-Disposition', 'attachment', filename=file.split('/')[-1]) # 添加附件到email message.attach(fileApart) # 邮件title title = mb_json['data']['title'] message['Subject'] = Header(title, 'utf-8') # 邮件抄送、收、发列表 send_to = _format_addr(mail_group['send_to']) send_Cc = _format_addr(mail_group['send_cc']) message['To'] = send_to message['Cc'] = send_Cc mail_user_name = mail_group['mail_user_name'] mail_user = mail_group['mail_user'] message['From'] = formataddr( (mail_user_name, mail_user)) # '王晨晨<*****@*****.**>' print(mail_user, send_to) print(message.as_string()) mail_host = mail_group['mail_host'] # 设置服务器 mail_user_pass = mail_group['mail_user_pass'] # 口令 # 发送尝试次数 for i in [1, 2, 3]: try: # 链接登录发送,与网络相关的内容可能都会失败,都需要重启链接 smtpObj = smtplib.SMTP_SSL(mail_host) smtpObj.login(mail_user, mail_user_pass) print(','.join([send_to, send_Cc])) smtpObj.sendmail( mail_user, mail_group['send_to'] + mail_group['send_cc'] + [mail_group['mail_user']], message.as_string()) print(datetime.datetime.now(), "邮件发送成功") break except: if i == 3: print(datetime.datetime.now(), '第{}次发送失败,返回错误信息'.format(i)) sleep(0.1) raise else: print(datetime.datetime.now(), '第{}次发送失败,{}秒后重试发送。'.format(i, 30)) traceback.print_exc() sleep(30) continue
def send_email(email_from, email_to, subject, text_body, html_body, file_name, file_data, src_email=None): """ Send email with text, html and attachment sections Args: email_from: address to send from email_to: address to send to subject: email subject line text_body: text/plain body of email html_body: text/html body of email, preferred display file_name: name of attachment file file_data: raw binary file data Returns: SES response object from AWS API Raises: FeedbackError: no body text provided or SES response is empty """ # Compose email with link or binary sesclient = boto3.client('ses', region_name='us-east-1') msg = MIMEMultipart() msg['Subject'] = str(subject) msg['From'] = email_from msg['To'] = email_to if html_body and text_body: email_content = MIMEMultipart('alternative') email_content.attach(MIMEText(text_body, 'plain', 'UTF-8')) email_content.attach(MIMEText(html_body, 'html', 'UTF-8')) msg.attach(email_content) elif text_body: msg.attach(MIMEText(text_body, 'plain', 'UTF-8')) else: raise ValidationError('No body text found') # attachment must be last part or clients won't show it if file_data: part = MIMEApplication(file_data) part.add_header('Content-Disposition', 'attachment', filename=file_name) msg.attach(part) try: if src_email == None: response = sesclient.send_raw_email( RawMessage={'Data': msg.as_string()}) else: response = sesclient.send_raw_email( Source=src_email, RawMessage={'Data': msg.as_string()}) except ClientError as error: raise AWSError('SendMail UnknownError: {}'.format(str(error))) if response is None: raise FeedbackError('Unknown Error: Return Value is None') return response
def send_email(): token = request.headers.get('Authorization', '') or '' json_data = request.get_json() if request.method == 'GET': data = {'status': 'is working'} return jsonify(data), 200 if request.method == 'POST': if not json_data or not token: data = { 'status': 'error', 'message': 'missing parameters' } return jsonify(data), 400 token_string = token.split() if not len(token_string) == 2 or not token_string[0] == 'Token': data = { 'status': 'error', 'message': 'user not authorized' } return jsonify(data), 401 if not 'to' in json_data or not 'html_body' in json_data or not 'subject' in json_data: data = { 'status': 'error', 'message': 'missing parameters' } return jsonify(data), 400 AWS_REGION = "us-west-2" SENDER = "*****@*****.**" RECIPIENT = json_data['to'] SUBJECT = json_data['subject'] BODY_HTML = json_data['html_body'] CC = [] if 'cc' in json_data: if json_data['cc']: CC = json_data['cc'] CHARSET = "UTF-8" client = boto3.client( 'ses', region_name=AWS_REGION ) msg = MIMEMultipart('mixed') msg['Subject'] = SUBJECT msg['From'] = SENDER msg['To'] = RECIPIENT if CC: msg['Cc'] = ','.join(CC) destinations = [RECIPIENT] if CC: for email in CC: destinations.append(email) msg_body = MIMEMultipart('alternative') htmlpart = MIMEText(BODY_HTML.encode(CHARSET), 'html', CHARSET) msg_body.attach(htmlpart) msg.attach(msg_body) if 'attachment' in json_data: if not 'filename' in json_data['attachment'] or not 'file' in json_data['attachment']: data = { 'status': 'error', 'message': 'missing parameters' } return jsonify(data), 400 filename = json_data['attachment']['filename'] file_pdf = json_data['attachment']['file'] file_pdf = file_pdf.encode('ascii') att = MIMEApplication(base64.decodestring(file_pdf)) att.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(att) try: response = client.send_raw_email( Source=SENDER, Destinations=destinations, RawMessage={ 'Data':msg.as_string(), }, ) except ClientError as e: print(e.response['Error']['Message']) data = { 'status': 'error', 'description': e.response['Error']['Message'] } return jsonify(data), 500 else: print("Email sent! Message ID:"), print(response['MessageId']) data = {'status': 'success'} return jsonify(data), 200