def make_string_payload(name, content): payload = MIMEApplication(content.encode("utf-8"), charset="utf-8") payload.add_header("Content-Disposition", "form-data", name=name) payload.set_type("text/plain") return payload
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 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 mail(self): if(self.guideFile==""): tkMessageBox.showinfo("Error", "Please select guidelines file") else: self.msg = MIMEMultipart() self.msg['Subject'] = 'Important: Exam Guiedlines' self.msg['From'] = '*****@*****.**' #msg['Reply-to'] = 'otroemail@dominio' self.msg['To'] = '*****@*****.**' # That is what u see if dont have an email reader: self.msg.preamble = 'Multipart massage.\n' # This is the textual part: self.part = MIMEText("Please find attched guidelines for exams.") self.msg.attach(self.part) # This is the binary part(The Attachment): self.part = MIMEApplication(open(self.guideFile,'rb').read()) self.part.add_header('Content-Disposition', 'attachment', filename=self.guideFile) self.msg.attach(self.part) # Create an instance in SMTP server self.server = SMTP("smtp.gmail.com",587) # Start the server: self.server.ehlo() self.server.starttls() self.server.login("*****@*****.**", "exammanage") # Send the email self.server.sendmail(self.msg['From'], self.msg['To'], self.msg.as_string()) tkMessageBox.showinfo("Success", "Guidelines have been successfully mailed.") self.dest1()
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 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 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 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 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 _sign_payload(self, payload, keyid=None, passphrase=None): payload = helper.normalize_payload(payload) plaintext = helper.email_as_string(payload) logging.debug('signing plaintext: ' + plaintext) signature = self.sign(plaintext, detach=True, keyid=keyid, passphrase=passphrase) if not signature: raise GPGProblem(_("Could not sign message (GnuPG " "did not return a signature)"), code=GPGCode.KEY_CANNOT_SIGN) micalg = helper.RFC3156_micalg_from_algo(signature.hash_algo) unencrypted_msg = MIMEMultipart( 'signed', micalg=micalg, protocol='application/pgp-signature' ) # wrap signature in MIMEcontainter stype = 'pgp-signature; name="signature.asc"' signature_mime = MIMEApplication(_data=str(signature), _subtype=stype, _encoder=encode_7or8bit) signature_mime['Content-Description'] = 'signature' signature_mime.set_charset('us-ascii') # add signed message and signature to outer message unencrypted_msg.attach(payload) unencrypted_msg.attach(signature_mime) unencrypted_msg['Content-Disposition'] = 'inline' return unencrypted_msg
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())
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 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 ( 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 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 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 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_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 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 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_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 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 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_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 _build_signed_message(self, message_dict): # this will sign the message text and attachments and puts them all together # Make a multipart message to contain the attachments and main message text. multipart_message = MIMEMultipart(_subtype="mixed") multipart_message.attach(MIMEText("%s\n" % message_dict['body'])) # Loop over the attachments if('attachments' in message_dict.keys()): for attachment in message_dict['attachments']: mime_base = MIMEBase('application', 'octet-stream') mime_base.set_payload(base64.b64encode(attachment['data'])) mime_base.add_header('Content-Transfer-Encoding', 'base64') mime_base.add_header('Content-Disposition', 'attachment', filename=attachment['filename']) multipart_message.attach(mime_base) # Removes the first line and replaces LF with CR/LF message_string = str(multipart_message).split('\n', 1)[1].replace('\n', '\r\n') # Make the signature component signature_text = str(self.gpg.sign(message_string, detach=True, keyid=self.config['sender']['fingerprint'], passphrase=self.config['sender']['key_password'])) signature_part = MIMEApplication(_data=signature_text, _subtype='pgp-signature; name="signature.asc"', _encoder=encode_7or8bit) signature_part['Content-Description'] = 'OpenPGP Digital Signature' signature_part.set_charset('us-ascii') # Make a box to put the message and signature in signed_message = MIMEMultipart(_subtype="signed", micalg="pgp-sha1", protocol="application/pgp-signature") signed_message.attach(multipart_message) signed_message.attach(signature_part) return signed_message
def sign(self, header, passphrase=None): """ multipart/signed +-> text/plain (body) +-> application/pgp-signature (signature) """ passphrase,pass_arg = self.passphrase_arg(passphrase) body = self.clearBodyPart() bfile = tempfile.NamedTemporaryFile() bfile.write(flatten(body)) bfile.flush() args = replace(pgp_sign_command, 'f', bfile.name) if PGP_SIGN_AS == None: pgp_sign_as = '<%s>' % source_email(header) else: pgp_sign_as = PGP_SIGN_AS args = replace(args, 'a', pgp_sign_as) args = replace(args, 'p', pass_arg) status,output,error = execute(args, stdin=passphrase) signature = output sig = MIMEApplication(_data=signature, _subtype='pgp-signature; name="signature.asc"', _encoder=encode_7or8bit) sig['Content-Description'] = 'signature' sig.set_charset('us-ascii') msg = MIMEMultipart('signed', micalg='pgp-sha1', protocol='application/pgp-signature') msg.attach(body) msg.attach(sig) msg['Content-Disposition'] = 'inline' return msg
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 testExtractOpenPGPHeaderIfInvalidAttachedKey(self): KEY = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n..." KEYURL = "https://leap.se/key.txt" OpenPGP = "id=12345678; url=\"%s\"; preference=signencrypt" % (KEYURL,) message = MIMEMultipart() message.add_header("from", ADDRESS_2) message.add_header("OpenPGP", OpenPGP) key = MIMEApplication("", "pgp-keys") key.set_payload(KEY) message.attach(key) self.fetcher._keymanager.put_raw_key = Mock( return_value=defer.fail(KeyAddressMismatch())) self.fetcher._keymanager.fetch_key = Mock() def put_raw_key_called(_): self.fetcher._keymanager.put_raw_key.assert_called_once_with( KEY, OpenPGPKey, address=ADDRESS_2) self.fetcher._keymanager.fetch_key.assert_called_once_with( ADDRESS_2, KEYURL, OpenPGPKey) d = self._do_fetch(message.as_string()) d.addCallback(put_raw_key_called) return d
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 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 enviar(lista_archivos: [], patrimonio, fecha_corte): msg = MIMEMultipart() lista_mensajes = [ ('<strong>Negocios con tipo de documento NULL</strong>', '<strong>Negocios Duplicados</strong>', '<strong>Cuotas Duplicadas</strong>', '<strong>Cuotas sin Negocio</strong>', '<strong>Numero de Negocio en NULL</strong>', '<strong>Movimientos ExtraFin sin Cuotas</strong>', '<strong>Movimientos sin Cuotas</strong>'), ('<strong>Remesas no estan generadas en la interfaz del Reports</strong>', '<strong>Remesas no estan generadas en la interfaz del Respaldo</strong>' ) ] # Parametros para enviar correo asunto = 'Revision de DATA para el proceso FIP_EJEC_DIARIO PATRIMONIO: %s FECHA DE CORTE: %s' % ( patrimonio, fecha_corte) password = "******" sistema = platform.platform() if sistema.startswith('Windows-10'): agregados = ', '.join(CORREOS['CC2']) destinatario = CORREOS['TO2'] else: agregados = ', '.join(CORREOS['CC']) destinatario = CORREOS['TO'] msg['To'] = destinatario msg['From'] = '*****@*****.**' msg['Cc'] = agregados msg['Subject'] = asunto envio = datetime.datetime.now() mensaje = '<h2 style="color: #2b2301;">Instrucciones para realizar correcciones de inconsistencias encontradas:</h2>' mensaje += '<p>Para el patrimonio %s y fecha de corte %s se encontraron las siguientes inconsistencias:' % ( patrimonio, fecha_corte) mensaje += '<ol style="line-height: 32px; list-style-type: square;">' for errores_encontrados in lista_archivos: mensaje += '<li style="clear: both;">%s</li>' % lista_mensajes[0][ errores_encontrados] mensaje += '</ol></p>' mensaje += '<h3 style="color: #2b2301;">Para corregir las inconsistencia se recomienda:</h3>' mensaje += '<ol style="line-height: 32px;">' mensaje += '<li style="clear: both;">Ejecutar los scripts .SQL enviados en orden.</li>' mensaje += '<li style="clear: both;">Realizar nuevamente la revisión para confirmar que no existan errores.</li>' mensaje += '<li style="clear: both;">Iniciar con el proceso diario.</li></ol>' mensaje += '<p><strong> </strong></p>' mensaje += '<p><strong>Nota: </strong>Si tiene alguna duda con las indicaciones enviadas por favor enviar un correo electronico a la direccion: <strong>[email protected]</strong><br/></p>' mensaje += '<p><strong>Enviado: </strong> %s</p>' % ( envio.strftime("%b %d %Y %H:%M")) body = MIMEText(str(mensaje), 'html') msg.attach(body) try: # Adjuntar CSV lista_nombres = ('negocios_documentoNULL_PAT-%s_FCORTE-%s' % (patrimonio, fecha_corte), 'negocios_duplicados_PAT-%s_FCORTE-%s' % (patrimonio, fecha_corte), 'cuotas_duplicadas_PAT-%s_FCORTE-%s' % (patrimonio, fecha_corte), 'cuotas_sin_negocio_PAT-%s_FCORTE-%s' % (patrimonio, fecha_corte), 'numero_negNULL_PAT-%s_FCORTE-%s' % (patrimonio, fecha_corte), 'movExtrafin_scuota_PAT-%s_FCORTE-%s' % (patrimonio, fecha_corte), 'movimiento_scuota_PAT-%s_FCORTE-%s' % (patrimonio, fecha_corte)) nombre_archivo = 'INCONSISTENCIAS_PAT-%s_FCORT-%s' % (patrimonio, fecha_corte) archivo_path = '%s/csv_data/%s.xlsx' % (PAT_BOT['PATH'], nombre_archivo) if (os.path.isfile(archivo_path)): fp = open(archivo_path, 'rb') att = MIMEApplication(fp.read(), _subtype="xlsx") fp.close() nombre_archivo = '%s.xlsx' % nombre_archivo att.add_header('Content-Disposition', 'attachment', filename=nombre_archivo) msg.attach(att) i = 1 for nombre_archivo in lista_archivos: archivo_path = '%s/scripts/%s.sql' % (PAT_BOT['PATH'], nombre_archivo) part = MIMEBase('application', "octet-stream") part.set_payload(open(archivo_path, "rb").read()) nombre_archivo = '%s_DELETE_%s.sql' % ( str(i), lista_nombres[nombre_archivo]) part.add_header('Content-Disposition', 'attachment', filename=nombre_archivo) msg.attach(part) i += 1 # Se envia el correo correos = agregados.split(',') + [destinatario] server = smtplib.SMTP('mail.imagicair.cl:587') server.starttls() server.login(msg['From'], password) server.sendmail(msg['From'], correos, msg.as_string()) server.quit() return ("%s" % (msg['To'])) except Exception as e: raise Exception("El correo no pudo enviarse, error: %s" % (e))
def send_request(self, service, args={}, file_args=None): ''' service: string args: dict ''' if self.session is not None: args.update({'session': self.session}) printDebug('Python:', args) json = python2json(args) printDebug('Sending json:', json) url = self.get_url(service) printDebug('Sending to URL:', url) # If we're sending a file, format a multipart/form-data if file_args is not None: # Make a custom generator to format it the way we need. from io import BytesIO try: # py3 from email.generator import BytesGenerator as TheGenerator except ImportError: # py2 from email.generator import Generator as TheGenerator 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]) class MyGenerator(TheGenerator): def __init__(self, fp, root=True): # don't try to use super() here; in py2 Generator is not a # new-style class. Yuck. TheGenerator.__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(): self._fp.write(('%s: %s\r\n' % (h, v)).encode()) # A blank line always separates headers from body self._fp.write('\r\n'.encode()) # 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 = BytesIO() 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} printDebug('Sending form data:', data) data = urlencode(data) data = data.encode('utf-8') printDebug('Sending data:', data) headers = {} request = Request(url=url, headers=headers, data=data) try: f = urlopen(request) txt = f.read() printDebug('Got json:', txt) result = json2python(txt) printDebug('Got result:', result) stat = result.get('status') printDebug('Got status:', stat) if stat == 'error': errstr = result.get('errormessage', '(none)') raise RequestError('server error message: ' + errstr) return result except HTTPError as e: printDebug('HTTPError', e) txt = e.read() open('err.html', 'wb').write(txt) printDebug('Wrote error text to err.html')
def startSend(self) -> bool: """Start send mail.""" from pineboolib.core.utils.utils_base import pixmap_fromMimeSource from pineboolib.core.settings import settings from pineboolib import application self.sendStarted.emit() self.sendTotalSteps.emit(len(self.attachments_) + 3) step = 0 self.changeStatus(self.tr("Componiendo mensaje"), State.Composing) outer = MIMEMultipart() outer["From"] = self.from_value_ or "" outer["To"] = self.to_ or "" if self.cc_ is not None: outer["Cc"] = self.cc_ if self.bcc_ is not None: outer["Bcc"] = self.bcc_ if self.organization_ is not None: outer["Organization"] = self.organization_ if self.priority_ > 0: outer["Priority"] = str(self.priority_) outer["Subject"] = self.subject_ or "" outer.preamble = "You will not see this in a MIME-aware mail reader.\n" mime_type_ = "text/plain" if self.mime_type_ is not None: mime_type_ = self.mime_type_ outer.add_header("Content-Type", mime_type_) outer.attach( MIMEText(self.body_ or "", mime_type_.split("/")[1], "utf-8")) step += 1 self.sendStepNumber.emit(step) # Adjuntar logo if settings.value("email/sendMailLogo", True): logo = settings.value( "email/mailLogo", "%s/logo_mail.png" % application.PROJECT.tmpdir) if not QtCore.QFile.exists(logo): logo = "%s/logo.png" % application.PROJECT.tmpdir Qt.QPixmap(pixmap_fromMimeSource("pineboo-logo.png")).save( logo, "PNG") fp = open(logo, "rb") logo_part = MIMEImage(fp.read()) fp.close() logo_part.add_header("Content-ID", "<image>") outer.attach(logo_part) # Ficheros Adjuntos for att in self.attachments_: try: with open(att, "rb") as fil: part = MIMEApplication(fil.read(), Name=basename(att)) part[ "Content-Disposition"] = 'attachment; filename="%s"' % basename( att) outer.attach(part) except IOError: logger.warning("Error al adjuntar el fichero %s." % att) return False # Envio mail composed = outer.as_string() step += 1 self.sendStepNumber.emit(step) try: s = smtplib.SMTP("%s:%s" % (self.mail_server_ or "", self.port_ or 25)) if self.connection_type_ == ConnectionType.TlsConnection: s.starttls() self.changeStatus("StartTTLS", State.StartTTLS) if self.user_ and self.password_: status_msg = "login." if self.auth_method_ == State.SendAuthLogin: self.changeStatus(status_msg, State.SendAuthLogin) elif self.auth_method_ == State.SendAuthPlain: self.changeStatus(status_msg, State.SendAuthPlain) s.login(self.user_, self.password_) self.changeStatus( status_msg, State.WaitingForAuthLogin if self.auth_method_ == State.SendAuthLogin else State.WaitingForAuthPlain, ) s.sendmail(self.from_value_ or "", self.to_ or "", composed) self.changeStatus("Correo enviado", State.SendOk) s.quit() return True except smtplib.SMTPHeloError: status_msg = "El servidor no ha respondido correctamente al saludo." self.changeStatus(status_msg, State.ClientError) return False # except smtplib.SMTPNotSupportedError: # status_msg = "El tipo de autenticación no está soportada por el servidor." # self.changeStatus(status_msg, State.ClientError) # return False except smtplib.SMTPConnectError: status_msg = "No se puede conectar al servidor SMTP." self.changeStatus(status_msg, State.ServerError) return False except smtplib.SMTPAuthenticationError: status_msg = "Error de autenticación SMTP." self.changeStatus(status_msg, State.ClientError) return False except smtplib.SMTPSenderRefused: status_msg = "Dirección de remitente rechazada." self.changeStatus(status_msg, State.ClientError) return False except smtplib.SMTPRecipientsRefused: status_msg = "Todas las direcciones de destinatarios se rechazaron." self.changeStatus(status_msg, State.ClientError) return False except smtplib.SMTPServerDisconnected: status_msg = "El servidor se desconecta inesperadamente." self.changeStatus(status_msg, State.ServerError) return False except smtplib.SMTPException: status_msg = "Error desconocido" self.changeStatus(status_msg, State.ClientError) return False except socket.gaierror: status_msg = ( "Servidor SMTP no encontrado.Verifique el nombre de host de su servidor SMTP." ) self.changeStatus(status_msg, State.SmtpError) return False except Exception as e: status_msg = "Error sending mail %s." % e return False
def send_Mail(self, message_plain_text, to, sender='me', subject=None, attachments=None, reply_message_id=None): ''' Usage - @send the mail to given address and attachments. Args - @message_plain_text : the plain text body of the mail. @to : mail address that going to be delivered. @sender : default as `me`. @subject : the subject of the mail, when reply_message_id has been given, will auto substitute into that reply threads subject. @attachments : list of attachments that will going to be sent. @reply_message_id : id of the message that going to be replied. Return - @return the MIME object. ''' message = MIMEMultipart() message['to'] = ' '.join(to) message['from'] = PROCESS_OWNER if reply_message_id: metadata = self.mail_service.users().messages().get( userId='me', id=reply_message_id, format='full').execute() threadId = metadata['threadId'] message['In-Reply-To'] = reply_message_id message['References'] = reply_message_id for payload in metadata['payload']['headers']: if payload['name'] == 'Subject': message['Subject'] = payload['value'] else: continue else: if not subject: print('''no subject provided for MIME''') return False else: message['subject'] = subject message.attach(MIMEText(message_plain_text, 'plain')) for attachment in attachments: if attachment: my_mimetype, encoding = mimetypes.guess_type(attachment) if my_mimetype is None or encoding is not None: my_mimetype = 'application/octet-stream' main_type, sub_type = my_mimetype.split('/', 1) if main_type == 'text': temp = open(attachment, 'r') attachement = MIMEText(temp.read(), _subtype=sub_type) temp.close() elif main_type == 'image': temp = open(attachment, 'rb') attachement = MIMEImage(temp.read(), _subtype=sub_type) temp.close() elif main_type == 'audio': temp = open(attachment, 'rb') attachement = MIMEAudio(temp.read(), _subtype=sub_type) temp.close() elif main_type == 'application' and sub_type == 'pdf': temp = open(attachment, 'rb') attachement = MIMEApplication(temp.read(), _subtype=sub_type) temp.close() else: attachement = MIMEBase(main_type, sub_type) temp = open(attachment, 'rb') attachement.set_payload(temp.read()) temp.close() encoders.encode_base64(attachement) filename = os.path.basename(attachment) attachement.add_header( 'Content-Disposition', 'attachment', filename=filename) # name preview in email message.attach(attachement) print(message) ## Part 4 encode the message (the message should be in bytes) message_as_bytes = message.as_bytes( ) # the message should converted from string to bytes. message_as_base64 = base64.urlsafe_b64encode( message_as_bytes) #encode in base64 (printable letters coding) raw = message_as_base64.decode( ) # need to JSON serializable (no idea what does it means) message = {'raw': raw} if reply_message_id: message['threadId'] = threadId try: message = self.mail_service.users().messages().send( userId=sender, body=message).execute() return message except (errors.HttpError): print('An error occurred: %s' % errors.HttpError)
m_from = username + "@" + hostname msg['From'] = m_from msg['To'] = ', '.join(s.mailto) msg.preamble = 'This is a milti-part message in MIME format.' # Add base text txt = sl.getstr() + "\n\nDetailed logs are attached.\n" txt = MIMEText(txt) msg.attach(txt) # Add attachments for tl in tarlogs: if tl: TL = open(tl, 'rb') if s.compresslog: att = MIMEApplication(TL.read(), 'gzip') else: att = MIMEText(TL.read(), 'plain', 'utf-8') TL.close() att.add_header('Content-Disposition', 'attachment', filename=os.path.basename(tl)) msg.attach(att) # Send the message if minPythonVersion(2, 6): smtp = smtplib.SMTP(timeout=300) else: smtp = smtplib.SMTP() #smtp.set_debuglevel(1) if s.smtphost:
def make_bytes_payload(name, content): payload = MIMEApplication(content) payload.add_header("Content-Disposition", "form-data", name=name) return payload
def send(self, body, title='', notify_type=NotifyType.INFO, attach=None, **kwargs): """ Perform Email Notification """ # Initialize our default from name from_name = self.from_name if self.from_name else self.app_desc # error tracking (used for function return) has_error = False if not self.targets: # There is no one to email; we're done self.logger.warning('There are no Email recipients to notify') return False # Create a copy of the targets list emails = list(self.targets) while len(emails): # Get our email to notify to_name, to_addr = emails.pop(0) # Strip target out of cc list if in To or Bcc cc = (self.cc - self.bcc - set([to_addr])) # Strip target out of bcc list if in To bcc = (self.bcc - set([to_addr])) try: # Format our cc addresses to support the Name field cc = [ formataddr((self.names.get(addr, False), addr), charset='utf-8') for addr in cc ] # Format our bcc addresses to support the Name field bcc = [ formataddr((self.names.get(addr, False), addr), charset='utf-8') for addr in bcc ] except TypeError: # Python v2.x Support (no charset keyword) # Format our cc addresses to support the Name field cc = [ formataddr( # pragma: no branch (self.names.get(addr, False), addr)) for addr in cc ] # Format our bcc addresses to support the Name field bcc = [ formataddr( # pragma: no branch (self.names.get(addr, False), addr)) for addr in bcc ] self.logger.debug('Email From: {} <{}>'.format( from_name, self.from_addr)) self.logger.debug('Email To: {}'.format(to_addr)) if cc: self.logger.debug('Email Cc: {}'.format(', '.join(cc))) if bcc: self.logger.debug('Email Bcc: {}'.format(', '.join(bcc))) self.logger.debug('Login ID: {}'.format(self.user)) self.logger.debug('Delivery: {}:{}'.format(self.smtp_host, self.port)) # Prepare Email Message if self.notify_format == NotifyFormat.HTML: content = MIMEText(body, 'html', 'utf-8') else: content = MIMEText(body, 'plain', 'utf-8') base = MIMEMultipart() if attach else content # Apply any provided custom headers for k, v in self.headers.items(): base[k] = Header(v, 'utf-8') base['Subject'] = Header(title, 'utf-8') try: base['From'] = formataddr( (from_name if from_name else False, self.from_addr), charset='utf-8') base['To'] = formataddr((to_name, to_addr), charset='utf-8') except TypeError: # Python v2.x Support (no charset keyword) base['From'] = formataddr( (from_name if from_name else False, self.from_addr)) base['To'] = formataddr((to_name, to_addr)) base['Cc'] = ','.join(cc) base['Date'] = \ datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S +0000") base['X-Application'] = self.app_id if attach: # First attach our body to our content as the first element base.attach(content) # Now store our attachments for attachment in attach: if not attachment: # We could not load the attachment; take an early # exit since this isn't what the end user wanted # We could not access the attachment self.logger.error( 'Could not access attachment {}.'.format( attachment.url(privacy=True))) return False self.logger.debug('Preparing Email attachment {}'.format( attachment.url(privacy=True))) with open(attachment.path, "rb") as abody: app = MIMEApplication(abody.read(), attachment.mimetype) app.add_header( 'Content-Disposition', 'attachment; filename="{}"'.format( Header(attachment.name, 'utf-8')), ) base.attach(app) # bind the socket variable to the current namespace socket = None # Always call throttle before any remote server i/o is made self.throttle() try: self.logger.debug('Connecting to remote SMTP server...') socket_func = smtplib.SMTP if self.secure and self.secure_mode == SecureMailMode.SSL: self.logger.debug('Securing connection with SSL...') socket_func = smtplib.SMTP_SSL socket = socket_func( self.smtp_host, self.port, None, timeout=self.socket_connect_timeout, ) if self.secure and self.secure_mode == SecureMailMode.STARTTLS: # Handle Secure Connections self.logger.debug('Securing connection with STARTTLS...') socket.starttls() if self.user and self.password: # Apply Login credetials self.logger.debug('Applying user credentials...') socket.login(self.user, self.password) # Send the email socket.sendmail(self.from_addr, [to_addr] + list(cc) + list(bcc), base.as_string()) self.logger.info( 'Sent Email notification to "{}".'.format(to_addr)) except (SocketError, smtplib.SMTPException, RuntimeError) as e: self.logger.warning( 'A Connection error occurred sending Email ' 'notification to {}.'.format(self.smtp_host)) self.logger.debug('Socket Exception: %s' % str(e)) # Mark our failure has_error = True finally: # Gracefully terminate the connection with the server if socket is not None: # pragma: no branch socket.quit() return not has_error
password = "******" sender = username recevier = ",".join(["*****@*****.**"]) #创建一个关于附件的对象 msg = MIMEMultipart() msg["From"] = sender msg["To"] = recevier msg["Subject"] = "带有附件的邮件" #创建一个关于正文的对象 text = MIMEText("today is a good day") #将附件和文本做整合 msg.attach(text) #设置附件部分 file = open("dog.jpg", "rb") imagePart = MIMEApplication(file.read()) #设置图片的相关信息 imagePart.add_header("Content-Disposition", "attachment", filename="dog.jpg") msg.attach(imagePart) smtpObj = smtplib.SMTP() smtpObj.connect("smtp.163.com") smtpObj.login(username, password) smtpObj.sendmail(sender, recevier, msg.as_string()) #退出服务器 smtpObj.quit()
def send_email(report_path): # 发件人和收件人 sender = '*****@*****.**' receiver = '*****@*****.**' # 所使用的用来发送邮件的SMTP服务器 smtpServer = 'smtp.163.com' # 发送邮箱的用户名和授权码(不是登录邮箱的密码) username = '******' password = '******' mail_title = '自动化测试报告' # mail_body = '这里是邮件的正文' # 创建一个实例 # msg = MIMEText(mail_body, 'plain', 'utf-8') # 邮件正文 msg = MIMEMultipart() msg['From'] = sender # 邮件上显示的发件人 msg['To'] = receiver # 邮件上显示的收件人 msg['Subject'] = Header(mail_title, 'utf-8') # 邮件主题 # ---这是文字部分 邮件正文--- part = MIMEText("接口自动化测试报告") msg.attach(part) # ---这是附件部分--- # attach_path = os.path.join(get_base_path(), 'result', 'report.html') attach_path = report_path part = MIMEApplication(open(attach_path, 'rb').read()) part.add_header('Content-Disposition', 'attachment', filename='report.html') msg.attach(part) ''' # xlsx类型附件 part = MIMEApplication(open('foo.xlsx', 'rb').read()) part.add_header('Content-Disposition', 'attachment', filename="foo.xlsx") msg.attach(part) # jpg类型附件 part = MIMEApplication(open('foo.jpg', 'rb').read()) part.add_header('Content-Disposition', 'attachment', filename="foo.jpg") msg.attach(part) # pdf类型附件 part = MIMEApplication(open('foo.pdf', 'rb').read()) part.add_header('Content-Disposition', 'attachment', filename="foo.pdf") msg.attach(part) # mp3类型附件 part = MIMEApplication(open('foo.mp3', 'rb').read()) part.add_header('Content-Disposition', 'attachment', filename="foo.mp3") msg.attach(part) ''' try: smtp = smtplib.SMTP() # 创建一个连接 smtp.connect(smtpServer) # 连接发送邮件的服务器 smtp.login(username, password) # 登录服务器 smtp.sendmail(sender, receiver, msg.as_string()) # 填入邮件的相关信息并发送 print("邮件发送成功!!!") smtp.quit() except smtplib.SMTPException: print("邮件发送失败!!!")
message.attach(textmessage) workLoc = os.path.join('D:\\', 'python', 'Python daima', 'interface') # #检查路径有效性 if (os.path.exists(workLoc)) & (os.path.isdir(workLoc)): #尝试改变当前工作路径: chdir(workLoc) else: print('路径无效,请从新检查') sys.exit() #尝试添加附件(File 里面可以随意更换任何图片、文件) File = '讲师评价系统.html' print("附件文件名为:%s" % File) FileLoc = os.path.join(workLoc, File) FileAtt = MIMEApplication(open(FileLoc, 'rb').read()) FileAtt.add_header('Content-Disposition', 'attachment', filename=File) message.attach(FileAtt) #发送邮件操作 smtpObj.sendmail(sender, receivers, message.as_string()) smtpObj.quit() print("发送成功!") # import smtplib # import email.utils # from email.mime.text import MIMEText # # class Msg(): # def __init__(self): # pass
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 sendEmail(to, result, attachment): # Replace [email protected] with your "From" address. # This address must be verified with Amazon SES. SENDER = "*****@*****.**" # Replace [email protected] with a "To" address. If your account # is still in the sandbox, this address must be verified. RECIPIENT = to # Specify a configuration set. If you do not want to use a configuration # set, comment the following variable, and the # ConfigurationSetName=CONFIGURATION_SET argument below. # CONFIGURATION_SET = "ConfigSet" # If necessary, replace us-west-2 with the AWS Region you're using for Amazon SES. AWS_REGION = "us-west-2" # The subject line for the email. SUBJECT = "Flight Checkin: {r}".format(r=result) # set the attachment filename ATTACHMENT = attachment # The email body for recipients with non-HTML email clients. BODY_TEXT = result # The HTML body of the email. BODY_HTML = "" # The character encoding for the email. CHARSET = "utf-8" # Create a new SES resource and specify a region. client = boto3.client('ses', region_name=AWS_REGION) # Create a multipart/mixed parent container. msg = MIMEMultipart('mixed') # Add subject, from and to lines. msg['Subject'] = SUBJECT msg['From'] = SENDER msg['To'] = RECIPIENT # Create a multipart/alternative child container. msg_body = MIMEMultipart('alternative') # 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. if ATTACHMENT: att = MIMEApplication(open(ATTACHMENT, 'rb').read()) msg.attach(att) # Add a header to tell the email client to treat this part as an attachment, # and to give the attachment a name. 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) #print(msg) try: #Provide the contents of the email. response = client.send_raw_email( Source=SENDER, Destinations=[RECIPIENT], RawMessage={ 'Data': msg.as_string(), }, # ConfigurationSetName=CONFIGURATION_SET ) # Display an error if something goes wrong. except ClientError as e: print(e.response['Error']['Message']) else: print("Email sent! Message ID:"), print(response['MessageId'])
def create_Message_with_attachment(sender, to, subject, message_text_plain, message_text_html, attached_file): """Create a message for an email. message_text: The text of the email message. attached_file: The path to the file to be attached. Returns: An object containing a base64url encoded email object. """ ##An email is composed of 3 part : #part 1: create the message container using a dictionary { to, from, subject } #part 2: attach the message_text with .attach() (could be plain and/or html) #part 3(optional): an attachment added with .attach() ## Part 1 message = MIMEMultipart( ) #when alternative: no attach, but only plain_text message['to'] = to message['from'] = sender message['subject'] = subject ## Part 2 (the message_text) # The order count: the first (html) will be use for email, the second will be attached (unless you comment it) message.attach(MIMEText(message_text_html, 'html')) message.attach(MIMEText(message_text_plain, 'plain')) ## Part 3 (attachement) # # to attach a text file you containing "test" you would do: # # message.attach(MIMEText("test", 'plain')) #-----About MimeTypes: # It tells gmail which application it should use to read the attachement (it acts like an extension for windows). # If you dont provide it, you just wont be able to read the attachement (eg. a text) within gmail. You'll have to download it to read it (windows will know how to read it with it's extension). #-----3.1 get MimeType of attachment #option 1: if you want to attach the same file just specify it’s mime types #option 2: if you want to attach any file use mimetypes.guess_type(attached_file) my_mimetype, encoding = mimetypes.guess_type(attached_file) # If the extension is not recognized it will return: (None, None) # If it's an .mp3, it will return: (audio/mp3, None) (None is for the encoding) #for unrecognized extension it set my_mimetypes to 'application/octet-stream' (so it won't return None again). if my_mimetype is None or encoding is not None: my_mimetype = 'application/octet-stream' main_type, sub_type = my_mimetype.split('/', 1) # split only at the first '/' # if my_mimetype is audio/mp3: main_type=audio sub_type=mp3 #-----3.2 creating the attachement #you don't really "attach" the file but you attach a variable that contains the "binary content" of the file you want to attach #option 1: use MIMEBase for all my_mimetype (cf below) - this is the easiest one to understand #option 2: use the specific MIME (ex for .mp3 = MIMEAudio) - it's a shorcut version of MIMEBase #this part is used to tell how the file should be read and stored (r, or rb, etc.) if main_type == 'text': print("text") temp = open( attached_file, 'r' ) # 'rb' will send this error: 'bytes' object has no attribute 'encode' attachement = MIMEText(temp.read(), _subtype=sub_type) temp.close() elif main_type == 'image': print("image") temp = open(attached_file, 'rb') attachement = MIMEImage(temp.read(), _subtype=sub_type) temp.close() elif main_type == 'audio': print("audio") temp = open(attached_file, 'rb') attachement = MIMEAudio(temp.read(), _subtype=sub_type) temp.close() elif main_type == 'application' and sub_type == 'pdf': temp = open(attached_file, 'rb') attachement = MIMEApplication(temp.read(), _subtype=sub_type) temp.close() else: attachement = MIMEBase(main_type, sub_type) temp = open(attached_file, 'rb') attachement.set_payload(temp.read()) temp.close() #-----3.3 encode the attachment, add a header and attach it to the message encoders.encode_base64( attachement) #https://docs.python.org/3/library/email-examples.html filename = os.path.basename(attached_file) attachement.add_header('Content-Disposition', 'attachment', filename=filename) # name preview in email message.attach(attachement) ## Part 4 encode the message (the message should be in bytes) message_as_bytes = message.as_bytes( ) # the message should converted from string to bytes. message_as_base64 = base64.urlsafe_b64encode( message_as_bytes) #encode in base64 (printable letters coding) raw = message_as_base64.decode( ) # need to JSON serializable (no idea what does it means) return {'raw': raw}
def sendEmailDirectMIME(self, msgtype, subjectstr, msgstr, recipient=None, files=None, deletefile=False): if recipient == None: recipient = self.EmailRecipientByType[msgtype] # update date dtstamp = datetime.datetime.now().strftime('%a %d-%b-%Y') # update time tmstamp = datetime.datetime.now().strftime('%I:%M:%S %p') msg = MIMEMultipart() if self.SenderName == None or not len(self.SenderName): msg['From'] = self.SenderAccount else: msg['From'] = self.SenderName + " <" + self.SenderAccount + ">" self.LogError(msg['From']) if self.UseBCC: msg['Bcc'] = recipient else: msg['To'] = recipient msg['Date'] = formatdate(localtime=True) msg['Subject'] = subjectstr body = '\n' + 'Time: ' + tmstamp + '\n' + 'Date: ' + dtstamp + '\n' + msgstr msg.attach(MIMEText(body, 'plain', 'us-ascii')) # if the files are not found then we skip them but still send the email try: for f in files or []: with open(f, "rb") as fil: part = MIMEApplication(fil.read(), Name=basename(f)) part[ 'Content-Disposition'] = 'attachment; filename="%s"' % basename( f) msg.attach(part) if deletefile: os.remove(f) except Exception as e1: self.LogErrorLine("Error attaching file in sendEmailDirectMIME: " + str(e1)) #self.LogError("Logging in: SMTP Server <"+self.SMTPServer+">:Port <"+str(self.SMTPPort) + ">") try: if self.SSLEnabled: session = smtplib.SMTP_SSL(self.SMTPServer, self.SMTPPort) session.ehlo() else: session = smtplib.SMTP(self.SMTPServer, self.SMTPPort) if not self.TLSDisable: session.starttls() session.ehlo # this allows support for simple TLS except Exception as e1: self.LogErrorLine("Error SMTP Init : SSL:<" + str(self.SSLEnabled) + ">: " + str(e1)) return False try: if self.EmailPassword != "": session.login(str(self.EmailAccount), str(self.EmailPassword)) if "," in recipient: multiple_recipients = recipient.split(",") session.sendmail(self.SenderAccount, multiple_recipients, msg.as_string()) else: session.sendmail(self.SenderAccount, recipient, msg.as_string()) except Exception as e1: self.LogErrorLine("Error SMTP sendmail: " + str(e1)) session.quit() return False session.quit() return True
try: if product.supplier.discount: unit_cost = unit_cost - ( (product.supplier.discount / Decimal('100')) * unit_cost) except Exception as e: print e print "\n" return unit_cost if __name__ == "__main__": supplyPDF = SupplyPDF() supplyPDF.create() msg = MIMEMultipart() msg['Subject'] = 'Supply Shopping List' msg['From'] = '*****@*****.**' msg['To'] = '*****@*****.**' part = MIMEApplication(open('Supplies_to_Buy.pdf', 'rb').read()) part.add_header('Content-Disposition', 'attachment', filename='shopping-list.pdf') msg.attach(part) connection = boto.connect_ses() result = connection.send_raw_email(msg.as_string(), source=msg['From'], destinations=[msg['To']]) print result
def send_request(self, service, args={}, file_args=None): if self.session is not None: args.update({'session': self.session}) json = python2json(args) url = self.get_url(service) # 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 >> self._fp, ('%s: %s\r\n' % (h, v)), # A blank line always separates headers from body print >> self._fp, '\r\n', # The _write_multipart method calls "clone" for the # sub-parts. 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} data = urlencode(data) headers = {} request = Request(url=url, headers=headers, data=data) response = urlopen(request) text = response.read() result = json2python(text) status = result.get('status') if status == 'error': error_message = result.get('errormessage', '(none)') log.error("Astrometry.net request error: %s" % error_message) raise RequestError('Server error message: ' + error_message) return result
def construct_mail(self): """ compiles the information contained in this envelope into a :class:`email.Message`. """ # Build body text part. To properly sign/encrypt messages later on, we # convert the text to its canonical format (as per RFC 2015). canonical_format = self.body.encode('utf-8') canonical_format = canonical_format.replace('\\t', ' ' * 4) textpart = MIMEText(canonical_format, 'plain', 'utf-8') # wrap it in a multipart container if necessary if self.attachments: inner_msg = MIMEMultipart() inner_msg.attach(textpart) # add attachments for a in self.attachments: inner_msg.attach(a.get_mime_representation()) else: inner_msg = textpart if self.sign: plaintext = crypto.email_as_string(inner_msg) logging.debug('signing plaintext: ' + plaintext) try: signatures, signature_str = crypto.detached_signature_for( plaintext, self.sign_key) if len(signatures) != 1: raise GPGProblem(("Could not sign message " "(GPGME did not return a signature)")) except gpgme.GpgmeError as e: if e.code == gpgme.ERR_BAD_PASSPHRASE: # If GPG_AGENT_INFO is unset or empty, the user just does # not have gpg-agent running (properly). if os.environ.get('GPG_AGENT_INFO', '').strip() == '': msg = "Got invalid passphrase and GPG_AGENT_INFO\ not set. Please set up gpg-agent." raise GPGProblem(msg) else: raise GPGProblem(("Bad passphrase. Is " "gpg-agent running?")) raise GPGProblem(str(e)) micalg = crypto.RFC3156_micalg_from_algo(signatures[0].hash_algo) outer_msg = MIMEMultipart('signed', micalg=micalg, protocol='application/pgp-signature') # wrap signature in MIMEcontainter stype = 'pgp-signature; name="signature.asc"' signature_mime = MIMEApplication(_data=signature_str, _subtype=stype, _encoder=encode_7or8bit) signature_mime['Content-Description'] = 'signature' signature_mime.set_charset('us-ascii') # add signed message and signature to outer message outer_msg.attach(inner_msg) outer_msg.attach(signature_mime) outer_msg['Content-Disposition'] = 'inline' else: outer_msg = inner_msg headers = self.headers.copy() # add Message-ID if 'Message-ID' not in headers: headers['Message-ID'] = [email.Utils.make_msgid()] if 'User-Agent' in headers: uastring_format = headers['User-Agent'][0] else: uastring_format = settings.get('user_agent').strip() uastring = uastring_format.format(version=__version__) if uastring: headers['User-Agent'] = [uastring] # copy headers from envelope to mail for k, vlist in headers.items(): for v in vlist: outer_msg[k] = encode_header(k, v) return outer_msg
def send_email(): uname = uname_receiver.get() email = Email_receiver.get() mail_server_passwd = mail_server_pw.get() if uname != "" and email != "" and mail_server_passwd != "": share_form.destroy() # Function: Share via email # dot = filename.rfind('.') ShareFilename = filename[: dot] # name of file to be shared ShareFileextension = filename[ dot + 1:] # file extension of the file to be shared EShareFilename = GCipherF.encrypt( padding(ShareFilename)).encode( "hex") # Encrypted name of file to be shared EShareFileextension = GCipherF.encrypt( padding(ShareFileextension)).encode( "hex") # Encrypted name of file to be shared cursor.execute( "SELECT * FROM Files WHERE Name = %s and Extension = %s and Owner = %s", ( EShareFilename, EShareFileextension, GUid, )) result = cursor.fetchone() Fid = result[0] # file id of the file to be shared result_Filecontent = result[ 3] # Encrypted file content of the file to be shared ShareFilecontent = depadding( GCipherF.decrypt(result_Filecontent.decode("hex")) ) # file content of the file to be shared OtherUsername = uname # id of user to whom file is shared OtherEmail = email # email of user to whom file is shared if OtherUsername == GUsername: # Error if the user try to share a file to himself/herself tkMessageBox.showwarning( "Warning", "Share to the owner is forbidden.") else: cursor.execute( "SELECT * FROM Users WHERE Name = %s", (OtherUsername, )) rc = cursor.rowcount if rc == 0: # Error if no such user tkMessageBox.showwarning( "Warning", "No such user.") else: # Send Encryption Key to the target user via email # try: sender = GEmail recipient = OtherEmail password = mail_server_passwd subject = "Encrypted File System: " + ShareFilename + "." + ShareFileextension + " shared by " + GUsername text = GUsername + " recently share a file to you.\n" message = MIMEMultipart() message.attach(MIMEText(text)) message['Subject'] = subject message['To'] = recipient message['From'] = sender message.attach( MIMEApplication( ShareFilecontent, name=os.path.basename( ShareFilename + "." + ShareFileextension))) server = smtplib.SMTP_SSL( "smtp.gmail.com", 465) server.login(sender, password) server.sendmail(message['From'], message['To'], message.as_string()) server.quit() tkMessageBox.showinfo( "COMP3335 - Encrypted File System", "share the " + ShareFilename + "." + ShareFileextension + " to " + recipient + " successfully") except smtplib.SMTPAuthenticationError: tkMessageBox.showwarning( "Warning", "Wrong password for email") except SMTPRecipientsRefused: tkMessageBox.showwarning( "Warning", "Invalid email") ########## ########## else: tkMessageBox.showwarning( "Warning", "Please enter all the information required.")
def attach_pdf(filename): with open(filename, 'rb') as f: pdf = f.read() msg = MIMEApplication(pdf, _subtype="pdf") return msg
''' #添付がある場合にはTrue、なければFalse attach = False if attach: msg = MIMEMultipart() msg["Subject"] = subject msg["To"] = mail_to msg["From"] = account msg.attach(MIMEText(text.encode("iso-2022-jp"), "plain", "iso-2022-jp")) # ファイルを添付 path = "./添付ファイル名" with open(path, "rb") as file: part = MIMEApplication(file.read(), Name=basename(path)) part['Content-Disposition'] = 'attachment; filename="%s"' % basename(path) msg.attach(part) else: msg = MIMEText(text.encode("iso-2022-jp"), "plain", "iso-2022-jp") msg["Subject"] = subject msg["To"] = mail_to msg["From"] = account # Gmailに接続 --- (*4) server = smtplib.SMTP_SSL("smtp.gmail.com", 465, context=ssl.create_default_context()) server.login(account, password)
def send(self): SENDER = "*****@*****.**" RECIPIENT = "*****@*****.**" AWS_REGION = "eu-west-1" SUBJECT = "Customer service contact info" ATTACHMENT = "abc.pdf" ATTACHMENT = ATTACHMENT.split(',') BODY_HTML = """\ <html> <head></head> <body> <h1>Hello!</h1> <p>Please see the attached file for a list of customers to contact.</p> </body> </html> """ CHARSET = "utf-8" # Create a new SES resource and specify a region. client = boto3.client('ses', region_name=AWS_REGION) # Create a multipart/mixed parent container. msg = MIMEMultipart('mixed') # Add subject, from and to lines. msg['Subject'] = SUBJECT msg['From'] = SENDER msg['To'] = RECIPIENT # Create a multipart/alternative child container. msg_body = MIMEMultipart('alternative') # 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. htmlpart = MIMEText(BODY_HTML.encode(CHARSET), 'html', CHARSET) msg.attach(msg_body) # Add the text and HTML parts to the child container. # Add the attachment to the parent container. msg_body.attach(htmlpart) for attachments in ATTACHMENT: att = MIMEApplication(open(attachments, 'rb').read()) att.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachments)) msg.attach(att) try: # Provide the contents of the email. response = client.send_raw_email( Source=SENDER, Destinations=[RECIPIENT], RawMessage={ 'Data': msg.as_string(), }, ) # Display an error if something goes wrong. except ClientError as e: print(e.response) else: print("Email sent! Message ID:"), print(response)
def toSendMail(): msg = MIMEMultipart() smtpserver = 'smtp-mail.outlook.com' #发送服务器 port = '587' #user='******' user = '******' #发送邮箱用户 passwd = 'Lpb201212' sender = '*****@*****.**' #发送邮箱地址 # reverser='*****@*****.**' #接收邮箱 reverser = '[email protected],' #'[email protected],[email protected]' reverser = string.splitfields(reverser, ",") subject = r'Python Mail Test with attach-邮件主题!' #主题中带中文的,则发件人名称正常 #邮件主题 #msg=MIMEText('<html><h1>你好!</h1></html>','html','utf-8') msg['Subject'] = Header(subject, 'utf-8') # 邮件内容正文 msg.attach(MIMEText(r'Zero项目自动化测试运行结果')) #添加附件 # filename="photo.png" # sendfile=open('geckodriver.log','a+').read() # att=MIMEText(sendfile,'base64','utf-8') # att["Content-Type"]='application/octet-stream' # att['Content-Disposition']='attchment;filename=%s'%filename.encode('gb2312') # msgRoot=MIMEMultipart('related','utf-8') # msgRoot['Subject']=subject # msgRoot.attach(att) # 调用截图函数 进行截图 #Screenshot() # # 添加附件就是加上一个MIMEBase,从本地读取一个图片: # with open('photo.png', 'rb') as f: # # 设置附件的MIME和文件名,这里是png类型: # mime = MIMEBase('image', 'png', filename='photo.png') # # 加上必要的头信息: # mime.add_header('Content-Disposition', 'attachment', filename='photo.png') # mime.add_header('Content-ID', '<0>') # mime.add_header('X-Attachment-Id', '0') # # 把附件的内容读进来: # mime.set_payload(f.read()) # # 用Base64编码: # encoders.encode_base64(mime) # # 添加到MIMEMultipart: # msg.attach(mime) # 把测试报告的附件加载进来 part = MIMEApplication(open(const.testreport, 'rb').read()) print('attach-testreport', const.testreport) part.add_header('Content-Disposition', 'attachment', filename='Autotest_result.xlsx') msg.attach(part) # 将测试案例的附件加载进来 part = MIMEApplication(open(const.testcasecp, 'rb').read()) print('attach-testcasecp', const.testcasecp) part.add_header('Content-Disposition', 'attachment', filename='Autotest_case.xlsx') msg.attach(part) smtp = smtplib.SMTP() smtp.connect(smtpserver, port) #使用port smtp.starttls() #SMTP 加密方法 STARTTLS 解决加密问题 smtp.ehlo() smtp.login(user, passwd) smtp.sendmail(sender, reverser, msg.as_string()) smtp.quit() print('Email send Sucess!') # toSendMail()
def sendfeedback(assignment_name, subject='MTH314 Assignment Feedback', graded_message=None, empty_feedback=None, cc='', bcc='', feedback_folder=f"./AutoGrader/feedback/", EMAILtest=True): import getpass import smtplib import subprocess import smtplib from email.mime.text import MIMEText from pathlib import Path from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from os.path import basename if (EMAILtest): print("TESTING Only, Emails will NOT be sent") else: for i in range(0, 3): print("WARNING, DANGER!!!!, Emails are being Sent") #Get the current username for the "from" email usr = getpass.getuser() fromAddress = usr + "@msu.edu" print(f"My email is {fromAddress}\n\n") #Pull in student names and emails from the nbgrader database command = "nbgrader db student list > temp.names" returned_output = subprocess.check_output(command, shell=True) s = smtplib.SMTP('smtp.egr.msu.edu') getdb = open("temp.names", 'r') lines = getdb.readlines() emails = [] tags = dict() tags['assignment_name'] = assignment_name for line in lines: part = line.split(' ') if not part[0] == 'There': folder = part[0] tags['last'] = part[1][1:-1] tags['first'] = part[2][:-1] toAddress = part[4][:-1] pth = Path(f"{feedback_folder}{folder}/{assignment_name}/") files = list(pth.glob('*.html')) if files: message = graded_message else: message = empty_feedback if not message == None: print(f"Emailing {tags['last']} {tags['first']}") newmessage = message for j, tag in enumerate(tags): newmessage = newmessage.replace(f"<<<{tag}>>>", tags[tag]) msg = MIMEMultipart() msg.attach(MIMEText(newmessage)) msg['Subject'] = subject msg['From'] = fromAddress msg['To'] = toAddress #Attach feedback if files: feedback_file = files[0] print(f"Attaching file {feedback_file}") with open(feedback_file, "rb") as attachment_file: part = MIMEApplication(attachment_file.read(), Name=basename(feedback_file)) # After the file is closed part[ 'Content-Disposition'] = f'attachment; filename="{basename(feedback_file)}"' msg.attach(part) else: feedback_file = "NONE" rcpt = toAddress.split(",") if cc: rcpt = cc.split(",") + rcpt msg['Cc'] = cc if bcc: rcpt = bcc.split(",") + rcpt msg['Bcc'] = bcc #TODO Add code to verify all << have been found #print(rcpt) if EMAILtest: print('To:', toAddress) print('From:', fromAddress) if cc: print('CC:', cc) if bcc: print('BCC:', bcc) print('Subject:', subject) print('Attachment:', feedback_file) print(newmessage) else: try: # Send the message via engineering SMTP server. print('Connecting to SMTP and sending message to', toAddress) s.sendmail(fromAddress, rcpt, msg.as_string()) except SMTPException: print("Error: unable to send email to", toAddress) print("\n\n") s.quit()
os.system('say "computation finished"') os.system('zip -r results.zip results_data') send_from = '*****@*****.**' send_to = ['*****@*****.**'] subject = "computation finished for %s p=%s, K=%s, " % (model, n_features, n_cut_points) text = "results available \n" files = "./results.zip" msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Subject'] = subject msg.attach(MIMEText(text)) with open(files, "rb") as fil: part = MIMEApplication(fil.read(), Name="results.zip") part['Content-Disposition'] = 'attachment; filename="results.zip"' msg.attach(part) try: smtp = smtplib.SMTP('smtp.upmc.fr') smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close() print("Successfully sent email") except smtplib.SMTPException: print("Error: unable to send email")
def send_email_smtp( # pylint: disable=invalid-name,too-many-arguments,too-many-locals to: str, subject: str, html_content: str, config: Dict[str, Any], files: Optional[List[str]] = None, data: Optional[Dict[str, str]] = None, images: Optional[Dict[str, bytes]] = None, dryrun: bool = False, cc: Optional[str] = None, bcc: Optional[str] = None, mime_subtype: str = "mixed", ) -> None: """ Send an email with html content, eg: send_email_smtp( '*****@*****.**', 'foo', '<b>Foo</b> bar',['/dev/null'], dryrun=True) """ smtp_mail_from = config["SMTP_MAIL_FROM"] smtp_mail_to = get_email_address_list(to) msg = MIMEMultipart(mime_subtype) msg["Subject"] = subject msg["From"] = smtp_mail_from msg["To"] = ", ".join(smtp_mail_to) msg.preamble = "This is a multi-part message in MIME format." recipients = smtp_mail_to if cc: smtp_mail_cc = get_email_address_list(cc) msg["CC"] = ", ".join(smtp_mail_cc) recipients = recipients + smtp_mail_cc if bcc: # don't add bcc in header smtp_mail_bcc = get_email_address_list(bcc) recipients = recipients + smtp_mail_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, imgdata in (images or {}).items(): image = MIMEImage(imgdata) 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 Enviar(self, remitente="", motivo="", destinatario="", mensaje="", archivo=None): "Generar un correo multiparte y enviarlo" try: to = [destinatario] if destinatario else self.Destinatarios msg = MIMEMultipart("related") msg["Subject"] = motivo or self.Motivo msg["From"] = remitente or self.Remitente msg["Reply-to"] = remitente or self.ResponderA msg["To"] = ", ".join(to) if self.CC: msg["CC"] = u", ".join(self.CC) to += self.CC if self.BCC: to += self.BCC msg.preamble = "Mensaje de multiples partes.\n" if mensaje: text = mensaje html = None else: text = self.MensajeTexto html = self.MensajeHTML if html: alt = MIMEMultipart("alternative") msg.attach(alt) part = MIMEText(text, "text") alt.attach(part) part = MIMEText(html, "html") alt.attach(part) else: part = MIMEText(text) msg.attach(part) if archivo: self.adjuntos.append(archivo) for archivo in self.adjuntos: part = MIMEApplication(open(archivo, "rb").read()) part.add_header( "Content-Disposition", "attachment", filename=os.path.basename(archivo), ) msg.attach(part) # print "Enviando email: %s a %s" % (msg['Subject'], msg['To']) self.smtp.sendmail(msg["From"], to, msg.as_string()) return True except Exception as e: ex = traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]) self.Traceback = "".join(ex) self.Excepcion = traceback.format_exception_only( sys.exc_info()[0], sys.exc_info()[1])[0] return False
def sendmail(self): try: #s = smtplib.SMTP() #create the mail server s = smtplib.SMTP_SSL(self.mail_host, 465) s.ehlo() print("begin---connecting") #s.connect(self.mail_host,587) print("connecting") s.login(self.mail_user, self.mail_pass) print("connected") for key in self.mailcontext: #print(key) #print(self.mailcontext[key]) mail = key print(type(key)) print(type(self.mailcontext[key])) #print(self.mailcontext[key]) #msg['To'] = Header(mail, 'utf-8') me = "Alex Wang<*****@*****.**>" #+self.mail_user #+"<"+ self.mail_user + "@"+self.mail_postfix msg = MIMEMultipart() msg['Form'] = me msg['To'] = mail msg['Subject'] = 'your title' context = self.mailcontext[key] for x in context: #print(x) puretext = MIMEText(x) #puretext = MIMEText(str(context)) #print(puretext) msg.attach(puretext) # jpg attached jpgpart = MIMEApplication( open('/home/alex/ext.jpg', 'rb').read()) jpgpart.add_header('Content-Disposition', 'attachment', filename='ext.jpg') msg.attach(jpgpart) # xlsx attached #xlsxpart = MIMEApplication(open('test.xlsx', 'rb').read()) #xlsxpart.add_header('Content-Disposition', 'attachment', filename='test.xlsx') #msg.attach(xlsxpart) # mp3 attached #mp3part = MIMEApplication(open('kenny.mp3', 'rb').read()) #mp3part.add_header('Content-Disposition', 'attachment', filename='benny.mp3') #msg.attach(mp3part) # pdf attached #part = MIMEApplication(open('/home/alex/Jian(Alex)wang (5th copy).pdf', 'rb').read()) #part.add_header('Content-Disposition', 'attachment', filename="Jian(Alex)wang (5th copy).pdf") #msg.attach(part) #print(mail) s.sendmail(me, mail, msg.as_string()) print("---send---") s.close() return True except Exception, e: print str(e) return False
def sendmail(): # 发件人地址,通过控制台创建的发件人地址 username = '******' # 发件人密码,通过控制台创建的发件人密码 password = '******' # 自定义的回复地址 # replyto = '***' # 收件人地址或是地址列表,支持多个收件人,最多30个 # rcptto = ['***', '***'] rcptto = '*****@*****.**' # 构建alternative结构 msg = MIMEMultipart('alternative') msg['Subject'] = Header('自定义信件主题来自阿里的测试 from 型谱 ssl测试').encode('utf-8') msg['From'] = '%s <%s>' % (Header('自定义发信昵称').encode('utf-8'), username) msg['To'] = rcptto # msg['Reply-to'] = replyto msg['Message-id'] = email.utils.make_msgid() msg['Date'] = email.utils.formatdate() # 构建alternative的text/plain部分 textplain = MIMEText('自定义TEXT纯文本部分', _subtype='plain', _charset='UTF-8') msg.attach(textplain) # 构建alternative的text/html部分 texthtml = MIMEText('自定义HTML超文本部分', _subtype='html', _charset='UTF-8') msg.attach(texthtml) # 附件类型 # xlsx 类型的附件 xlsxpart = MIMEApplication(open('shortcut.png', 'rb').read()) xlsxpart.add_header('Content-Disposition', 'attachment', filename=Header("shortcut.png", "utf-8").encode()) msg.attach(xlsxpart) # 发送邮件 try: # client = smtplib.SMTP() # python 2.7以上版本,若需要使用SSL,可以这样创建client client = smtplib.SMTP_SSL() # SMTP普通端口为25或80 client.connect('smtp.mxhichina.com', 465) # 开启DEBUG模式 client.set_debuglevel(0) client.login(username, password) # 发件人和认证地址必须一致 # 备注:若想取到DATA命令返回值,可参考smtplib的sendmaili封装方法: # 使用SMTP.mail/SMTP.rcpt/SMTP.data方法 client.sendmail(username, rcptto, msg.as_string()) client.quit() print('邮件发送成功!') except smtplib.SMTPConnectError as e: print('邮件发送失败,连接失败:', e.smtp_code, e.smtp_error) except smtplib.SMTPAuthenticationError as e: print('邮件发送失败,认证错误:', e.smtp_code, e.smtp_error) except smtplib.SMTPSenderRefused as e: print('邮件发送失败,发件人被拒绝:', e.smtp_code, e.smtp_error) except smtplib.SMTPRecipientsRefused as e: print('邮件发送失败,收件人被拒绝:', e.smtp_code, e.smtp_error) except smtplib.SMTPDataError as e: print('邮件发送失败,数据接收拒绝:', e.smtp_code, e.smtp_error) except smtplib.SMTPException as e: print('邮件发送失败, ', e.message) except Exception as e: print('邮件发送异常, ', str(e))
def send_email(self, text): #text = self.claw_content() #open('b.txt', 'w').write(str(text[1]) + '\n' + str(text[0]) + '\n') username = '******' # input("请输入账号:") password = '******' # input("请输入密码:") sender = username # sender='' receiver = [ '*****@*****.**' ] # '*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**' if sender == '': username = str( raw_input( "Please Input Sender Email Address,for example:[email protected] \n" )) sender = username password = str(raw_input("Please Input Sender Password \n")) receiver.append( str( raw_input( "Please Input Receiver Address,for example:[email protected] \n" ))) iRec = 1 while iRec > 0: CmdRec = '' #raw_input("Whether you want to add another Receiver Address(default n)? \n") if CmdRec == 'y' or CmdRec == 'yes': iRec = 1 receiver.append( str( raw_input( "Please Input Receiver Address,for example:[email protected] \n" ))) else: iRec = 0 ConfirmRec = '' #raw_input("Confirm? \n") if ConfirmRec == 'n' or ConfirmRec == 'no': print("What Do You Want? Maybe run this program again.\n") exit(1) else: for rece in receiver: print("OK \n" + username + " sendto " + rece) # 创建一个带附件的实例 msg = MIMEMultipart() # msg = MIMEText(str(text), 'plain', 'utf-8') msg['From'] = formataddr(['user', sender]) # 括号里的对应发件人邮箱昵称、发件人邮箱账号 msg['To'] = ",".join(receiver) # 括号里的对应收件人邮箱昵称、收件人邮箱账号 subject_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') subject = '宣讲会信息' msg['Subject'] = subject # 邮件正文内容 # print str(text[0]) realText = '\n' + str(subject_time) + ':主人,有人来招人啦!^—^\n' + '海投网:' + str( text[1] ) + '.' #+str(text[0])#'地大就业网招聘公告:'+str(text1[1])+'地大就业网gis等招聘信息:'+str(text2[1])+'.'#+str(text1[0])+'\n'+str(text2[1])+'\n'+str(text2[0]) print realText msg.attach(MIMEText(realText, 'plain', 'utf-8')) # 构造附件1,传送当前目录下的 test.txt 文件 att1 = MIMEApplication(open('b.txt', 'rb').read()) # 这里的filename可以任意写,写什么名字,邮件中显示什么名字 att1.add_header('Content-Disposition', 'attachment', filename='hjx.txt') msg.attach(att1) # # 构造附件1,传送当前目录下的 test.txt 文件 # att2 = MIMEApplication(open('b1.txt', 'rb').read()) # # 这里的filename可以任意写,写什么名字,邮件中显示什么名字 # att2.add_header('Content-Disposition', 'attachment', filename='b1.txt') # msg.attach(att2) # att3 = MIMEApplication(open('b2.txt', 'rb').read()) # # 这里的filename可以任意写,写什么名字,邮件中显示什么名字 # att3.add_header('Content-Disposition', 'attachment', filename='b2.txt') # msg.attach(att3) smtpserver = 'smtp.126.com' try: smtp = smtplib.SMTP(smtpserver, 25) smtp.starttls() smtp.login(username, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit() print(u"邮件发送成功") except smtplib.SMTPException, e: print(u"Error: 无法发送邮件:" + str(e)) smtp.quit() try: username = '******' # input("请输入账号:") password = '******' # input("请输入密码:") sender = username # sender='' # receiver = [ '*****@*****.**','*****@*****.**','*****@*****.**'] # '*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**' msg['From'] = formataddr(['lishulin', sender]) # 括号里的对应发件人邮箱昵称、发件人邮箱账号 msg['To'] = ",".join(receiver) # 括号里的对应收件人邮箱昵称、收件人邮箱账号 smtpserver = 'smtp.163.com' smtp = smtplib.SMTP(smtpserver, 25) smtp.starttls() smtp.login(username, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit() print(u"邮件发送成功") except smtplib.SMTPException, e1: print(u"Error: 无法发送邮件:" + str(e1)) smtp.quit() try: username = '******' # input("请输入账号:") password = '******' # input("请输入密码:") sender = username # sender='' # receiver = [ '*****@*****.**','*****@*****.**','*****@*****.**'] # '*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**' msg['From'] = formataddr(['*****@*****.**', sender]) # 括号里的对应发件人邮箱昵称、发件人邮箱账号 msg['To'] = ",".join(receiver) # 括号里的对应收件人邮箱昵称、收件人邮箱账号 smtpserver = 'smtp.sina.cn' smtp = smtplib.SMTP(smtpserver, 25) smtp.starttls() smtp.login(username, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit() print(u"邮件发送成功") except smtplib.SMTPException, e2: print(u"Error: 无法发送邮件:" + str(e2)) smtp.quit()