def send_mail(send_from, send_to, subject, text, filename=None): msg = emm.MIMEMultipart() msg['From'] = send_from msg['To'] = send_to msg['Date'] = eu.formatdate(localtime=True) msg['Subject'] = subject msg.attach(emt.MIMEText(text)) # Attach the given file. if filename is not None: with open(filename, "rb") as f: part = ema.MIMEApplication(f.read(), Name=os.path.basename(f)) part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f) msg.attach(part) # Get the recipient MX record. domain = send_to.split('@')[1] server = get_mx_record(domain) smtp = smtplib.SMTP(server) # Send smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def sender_mail(): smt_p = smtplib.SMTP() # 创建对象 smt_p.connect(host='smtp.qq.com', port=25) # 设置smtp服务器 sender = '*****@*****.**' password = "******" # 在qq邮箱设置开启SMTP服务并复制授权码到password smt_p.login(sender, password) # 进行邮箱登录一次,填写你本人的邮箱 receiver_addresses, count_num = [ '*****@*****.**', '*****@*****.**' ], 1 for email_address in receiver_addresses: # 表格中邮箱格式不正确,如有空字符,在发邮件的时候会出现异常报错,捕获到这些异常就跳过 try: msg = multipart.MIMEMultipart() msg['From'] = "zhenguo" # 设置发邮件人 msg['To'] = email_address # 收件人 # msg['Cc'] = '*****@*****.**' msg['subject'] = header.Header('通知', 'utf-8') # 主题名称 msg.attach( text.MIMEText( '您好!\n这是一封测试邮件,使用Python实现自动发邮件,请勿回复本邮件功能~\n\n 祝您工作愉快!', 'plain', 'utf-8')) xlsxpart = application.MIMEApplication( open(r'./data/email_test.xlsx', 'rb').read()) xlsxpart.add_header('Content-Disposition', 'attachment', filename='1.xlsx') msg.attach(xlsxpart) # 添加邮件的附件 smt_p.sendmail(sender, email_address, msg.as_string()) # 发送邮件 time.sleep(10) # sleep10秒避免发送频率过快,可能被判定垃圾邮件。 print('第%d次发送给%s' % (count_num, email_address)) count_num = count_num + 1 except Exception as e: print('第%d次给%s发送邮件异常' % (count_num, email_address)) continue smt_p.quit()
def test_encoding_multipart(self): from email.mime import application from email.mime import multipart from email.mime import nonmultipart from repoze.sendmail._compat import b from repoze.sendmail._compat import encodestring from repoze.sendmail._compat import from_octets message = multipart.MIMEMultipart('alternative') utf_8_encoded = b('mo \xe2\x82\xac') utf_8 = utf_8_encoded.decode('utf-8') plain_string = utf_8 plain_part = nonmultipart.MIMENonMultipart('plain', 'plain') plain_part.set_payload(plain_string) message.attach(plain_part) html_string = '<p>' + utf_8 + '</p>' html_part = nonmultipart.MIMENonMultipart('text', 'html') html_part.set_payload(html_string) message.attach(html_part) binary = from_octets([x for x in range(256)]) binary_b64 = encodestring(binary) binary_part = application.MIMEApplication(binary) message.attach(binary_part) encoded = self._callFUT(message) self.assertTrue(encodestring(plain_string.encode('utf-8')) in encoded) self.assertTrue(encodestring(html_string.encode('utf-8')) in encoded) self.assertTrue(binary_b64 in encoded)
def send_mail(config, subject, message, files_to_attach): # unpack some config stuff email = config["email_config"]["email"] password = config["email_config"]["password"] email_name = config["email_config"]["name"] to_list = config["mailing_list"]["emails"] to_list_name = config["mailing_list"]["name"] # connect to gmail server = smtp('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(email, password) # build up the message msg = multipart.MIMEMultipart() msg.attach(text.MIMEText(message)) msg['From'] = email_name msg['To'] = to_list_name msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject for f in files_to_attach: part = base.MIMEBase('application', "octet-stream") with open(f, "rb") as fp: part.set_payload(fp.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(f))) msg.attach(part) server.sendmail(email, to_list, msg.as_string()) server.quit()
def test_encoding_multipart_quopri(self): import quopri from email.mime import multipart from email.mime import nonmultipart from repoze.sendmail._compat import b latin_1_encoded = b('LaPe\xf1a') latin_1 = latin_1_encoded.decode('latin_1') plain_string = 'I know what you did last ' + latin_1 message = multipart.MIMEMultipart('alternative') plain_part = nonmultipart.MIMENonMultipart('plain', 'plain') plain_part.set_payload(plain_string) message.attach(plain_part) html_string = '<p>' + plain_string + '</p>' html_part = nonmultipart.MIMENonMultipart('text', 'html') html_part.set_payload(html_string) message.attach(html_part) encoded = self._callFUT(message) self.assertEqual( encoded.count(quopri.encodestring(plain_string.encode('latin_1'))), 2)
def send_fic(url: str, email_address: str, password: str, kindle_email): port = 587 fic_filename = download_mobi_and_get_file_name(url) print('downloaded!') email = smtplib.SMTP('smtp.gmail.com', port) email.ehlo() email.starttls() # password = input('Password:'******'From'] = email_address msg['To'] = kindle_email msg['Subject'] = '' attachment = open(fic_filename, 'rb') p = base.MIMEBase('application', 'octet-stream') p.set_payload(attachment.read()) encoders.encode_base64(p) p.add_header('Content-Disposition', "attachment; filename= %s" % fic_filename) msg.attach(p) text = msg.as_string() email.sendmail(email_address, kindle_email, text) print('sent!') email.quit() attachment.close() os.remove(fic_filename)
def __ConfigureMultipartRequest(self, http_request): """Configure http_request as a multipart request for this upload.""" # This is a multipart/related upload. msg_root = mime_multipart.MIMEMultipart('related') # msg_root should not write out its own headers setattr(msg_root, '_write_headers', lambda self: None) # attach the body as one part msg = mime_nonmultipart.MIMENonMultipart( *http_request.headers['content-type'].split('/')) msg.set_payload(http_request.body) msg_root.attach(msg) # attach the media as the second part msg = mime_nonmultipart.MIMENonMultipart(*self.mime_type.split('/')) msg['Content-Transfer-Encoding'] = 'binary' msg.set_payload(self.stream.read()) msg_root.attach(msg) # encode the body: note that we can't use `as_string`, because # it plays games with `From ` lines. fp = StringIO.StringIO() g = email_generator.Generator(fp, mangle_from_=False) g.flatten(msg_root, unixfrom=False) http_request.body = fp.getvalue() multipart_boundary = msg_root.get_boundary() http_request.headers['content-type'] = ( 'multipart/related; boundary=%r' % multipart_boundary)
def execute(self, *args, **kwargs): userdata = mime_multipart.MIMEMultipart() rabbit_nodes = { "rabbit-node-%d" % i: kwargs["%s%d" % (self.node_ip_prefix, i)] for i in range(self.node_count) } cloud_config = self.cloud_config_template.render( node_name=kwargs['node_name']) sub_message = mime_text.MIMEText(cloud_config, 'cloud-config', sys.getdefaultencoding()) sub_message.add_header('Content-Disposition', 'attachment; filename="cloud_config"') userdata.attach(sub_message) userdata_inputs = { 'rabbit_nodes': rabbit_nodes, 'erlang_cookie': kwargs['erlang_cookie'], 'default_rabbit_user': kwargs['default_rabbit_user'], 'default_rabbit_pass': kwargs['default_rabbit_pass'], 'cluster_id': kwargs['cluster_id'], } script = self.userdata_template.render(userdata_inputs) sub_message = mime_text.MIMEText(script, 'x-shellscript', sys.getdefaultencoding()) sub_message.add_header('Content-Disposition', 'attachment; filename="setup_rabbitmq.sh"') userdata.attach(sub_message) return userdata.as_string()
def return_attachment(gmail, item_dict): ''' Creates an attachment and then sends it to the string gmail, from the dictionary item_dict. Uses the smtp library. ''' file = open("return_attachment.txt", "w") for key, value in item_dict.items(): file.write(str(key) + " " + str(value) + "\n") file.close() del (file) #for some reason, you have to remove the variable and redo it. mjsg = multipart.MIMEMultipart() #create email base. mjsg['From'] = "*****@*****.**" mjsg['To'] = gmail mjsg['Subject'] = "Smart_list" attn = open("return_attachment.txt", "r") #create attachments. attachment = text.MIMEText(attn.read()) attachment.add_header('Content-Disposition', 'attachment', filename=attn.name) mjsg.attach(attachment) #attach attachment... I love documentation. try: context = ssl.create_default_context() #send email and exit smtp = smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) smtp.login("*****@*****.**", "MatterH27h") smtp.sendmail("*****@*****.**", gmail, mjsg.as_string()) smtp.close() except: print( "Some sort of network failure happened trying to send the eamil." ) #If you get this it means you have problems with either the network or the 'gmail' (email) input.
def send_mail(to_list, sub, content, filepath=''): mail_host = "smtp.163.com" #使用的邮箱的smtp服务器地址 mail_user = "******" #用户名 mail_pass = "******" #密码 msg = multipart.MIMEMultipart() msg['Subject'] = sub #邮件标题 msg['From'] = mail_user msg['To'] = ";".join(to_list) #将收件人列表以‘;’分隔 if os.path.exists(filepath): fname = "attachment; filename=" + os.path.basename(filepath) print(fname) fs = open(filepath, 'r', encoding='utf-8') logs = fs.read() fs.close() att = MIMEText(logs, 'plain', 'utf-8') att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = fname msg.attach(att) content = content + '\n\n\n' + logs print(content) else: pass text_con = MIMEText(content, 'plain', "utf-8") msg.attach(text_con) try: server = smtplib.SMTP() server.connect(mail_host) #连接服务器 server.login(mail_user, mail_pass) #登录操作 server.sendmail(mail_user, to_list, msg.as_string()) #print('邮件发送成功') server.close() return True except Exception as e: print('邮件发送失败:', str(e)) return False
def send_email(message_body, subject, sender, recipients, server, attachments=[], message_body_type='plain'): msg_root = mimemultipart.MIMEMultipart('mixed') msg_root['Date'] = email.utils.formatdate(localtime=True) msg_root['From'] = sender msg_root['To'] = ', '.join(recipients) msg_root['Subject'] = email.header.Header(subject, 'utf-8') msg_txt = mimetext.MIMEText(message_body, message_body_type, 'utf-8') msg_root.attach(msg_txt) for attachment in attachments: filename = os.path.basename(attachment) with open(attachment, 'rb') as f: msg_attach = mimebase.MIMEBase('application', 'octet-stream') msg_attach.set_payload(f.read()) email.encoders.encode_base64(msg_attach) msg_attach.add_header('Content-Disposition', 'attachment', filename=(email.header.Header( filename, 'utf-8').encode())) msg_root.attach(msg_attach) server.send_message(msg_root)
def get_message(self): if self.message: return self.message subparts = [] for item in self.properties[self.PARTS]: config = item.get(self.CONFIG) part_type = item.get(self.TYPE, self.TEXT) part = config if uuidutils.is_uuid_like(config): try: sc = self.rpc_client().show_software_config( self.context, config) except Exception as ex: self.rpc_client().ignore_error_named(ex, 'NotFound') else: part = sc[rpc_api.SOFTWARE_CONFIG_CONFIG] if part_type == self.MULTIPART: self._append_multiparts(subparts, part) else: filename = item.get(self.FILENAME, '') subtype = item.get(self.SUBTYPE, '') self._append_part(subparts, part, subtype, filename) mime_blob = multipart.MIMEMultipart(_subparts=subparts) self.message = mime_blob.as_string() return self.message
def email_file(self,filename=None,showname=None,img=None,body=None,subject=None,sendername=None): #此处直接定义一个发送图片+文件的方法 self.text_obj = multipart.MIMEMultipart() # 附件形式 # 添加一个文件 if filename: with open(filename, 'rb') as fo: fo_str = fo.read() attr = text.MIMEText(fo_str, _charset='utf-8') attr["Content-Type"] = 'application/octet-stream' if not showname: showname=os.path.basename(filename) # attr['Content-Disposition'] = 'attachment; filename=%s'%showname # 没有这个不显示附件位置··WWWW是名称,可以参数格式化 attr.add_header('Content-Disposition', 'attachment', filename=('gbk', '', showname)) self.text_obj.attach(attr) if not subject: subject='附件--%s'%showname if img and body: self.text_obj.attach(text.MIMEText(body, 'html', 'utf-8')) # 显示一个图片 with open(img, 'rb') as fo: im_str = fo.read() attr = image.MIMEImage(im_str) # attr.add_header('Content-ID', '<image1>') #指定图片 img_id = re.findall(r'cid:(\w+).*', body)[0] attr['Content-ID'] = '<%s>'%img_id # 这个是和body中的image1一致 self.text_obj.attach(attr) if not subject: subject='图片--%s'%(os.path.basename(img)) self.__email_conf(subject,sendername) self.__send_eamil()
def create_message(self, recipient: str, subject: str, new_entries: list): """ Send an email using the Gmail API with one or more attachments. Args: to: The to recipient of the email. Example: [email protected] subject: The subject of the email. service: An established object with authorised access to the Gmail API for sending emails. message_text: The body of the message to be sent. Raises: N/A Returns: message: A message in the proper format, ready to be sent by the send_email function. """ # Create the message string from LogEntry objects message_text = f"New log entries have been fetched from {self.isp_address}:\n\n" for new_entry in new_entries: message_text.append(new_entry) # Create an email message mime_message = multipart.MIMEMultipart() mime_message["to"] = recipient mime_message["subject"] = subject mime_message.attach(text.MIMEText(message_text, "plain")) # Format message dictionary, ready for sending message = { "raw": base64.urlsafe_b64encode(mime_message.as_bytes()).decode() } return message
def _getbundlemsgs(repo, sender, bundle, **opts): """Get the full email for sending a given bundle This function returns a list of "email" tuples (subject, content, None). The list is always one message long in that case. """ ui = repo.ui _charsets = mail._charsets(ui) subj = opts.get('subject') or prompt(ui, b'Subject:', b'A bundle for your repository') body = _getdescription(repo, b'', sender, **opts) msg = emimemultipart.MIMEMultipart() if body: msg.attach(mail.mimeencode(ui, body, _charsets, opts.get('test'))) datapart = emimebase.MIMEBase('application', 'x-mercurial-bundle') datapart.set_payload(bundle) bundlename = b'%s.hg' % opts.get('bundlename', b'bundle') datapart.add_header( 'Content-Disposition', 'attachment', filename=encoding.strfromlocal(bundlename), ) emailencoders.encode_base64(datapart) msg.attach(datapart) msg['Subject'] = mail.headencode(ui, subj, _charsets, opts.get('test')) return [(msg, subj, None)]
def applyInterview(): if 'username' not in session.keys(): return signin(None, "/apply_interview/") data = request.form.to_dict() print(data) fromaddr = "*****@*****.**" msg = multipart.MIMEMultipart() msg['From'] = "interview Geek" # msg['To'] = toaddr toaddr = data["email"] msg['Subject'] = "New response to your interview circular" msg_body = "A user named " + session[ "username"] + " from interview Geek responds to your interview circular!!! \n\n Thank You." msg.attach(mailText.MIMEText(msg_body, 'plain')) server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.ehlo() server.login("*****@*****.**", "iplab2019") text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit() return redirect("/circular")
def mp_userdata_from_files(files, compress=False, multipart_mime=None): outer = multipart_mime or multipart.MIMEMultipart() mtypes = [] for i, fp in enumerate(files): mtype = _get_type_from_fp(fp) mtypes.append(mtype) maintype, subtype = mtype.split('/', 1) if maintype == 'text': # Note: we should handle calculating the charset msg = text.MIMEText(fp.read(), _subtype=subtype) fp.close() else: if hasattr(fp, 'name'): fp = open(fp.name, 'rb') msg = base.MIMEBase(maintype, subtype) msg.set_payload(fp.read()) fp.close() # Encode the payload using Base64 encoders.encode_base64(msg) # Set the filename parameter fname = getattr(fp, 'name', "sc_%d" % i) msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(fname)) outer.attach(msg) userdata = outer.as_string() if compress: s = StringIO.StringIO() gfile = gzip.GzipFile(fileobj=s, mode='w') gfile.write(userdata) gfile.close() s.seek(0) userdata = s.read() return userdata
def SendEmail(user, psw, subject, AnnexList, toaddr, content, emailsrv): # print subject try: #创建一个带附件的实例 msg = multipart.MIMEMultipart() #构造附件 for Annex in AnnexList: annexfile = open(Annex, 'rb') annexdata = annexfile.read() annexfile.close() att = text.MIMEText(annexdata, 'base64', 'gb2312') att['Content-Type'] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename="%s"' % ( os.path.basename(Annex)) msg.attach(att) #构造正文 att = text.MIMEText(content, 'base64', 'gb2312') att['Content-Type'] = 'text/plain' att["Content-Transfer-Encoding"] = '7bit' msg.attach(att) #加邮件头 msg['to'] = toaddr msg['from'] = user msg['subject'] = header.Header(subject, 'gb2312') s = smtplib.SMTP(emailsrv) s.login(user, psw) s.sendmail(msg['from'], toaddr, msg.as_string()) s.quit() except: return False, "%s" % traceback.format_exc() return True, ""
def broadcast(self): sender = '*****@*****.**' receivers = ['*****@*****.**', '*****@*****.**'] message = multipart.MIMEMultipart('alternative') message[ 'Subject'] = 'Market Statistics of Last Trading Day ({})'.format( self.__last_date) main_text = """ Volume weighted average spread: ${:<10.4f} SPY 5-tick momentum index: {:<10.4f} """.format(self.vol_avg_spread(), self.spy_accuracy(self.__spy_df.price, 0.05)) message.attach(text.MIMEText(main_text, 'plain')) try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message.as_string()) smtpObj.quit() print("Successfully sent email") except smtplib.SMTPException: print("Error: cannot send email")
def _Execute(self, http): """Serialize batch request, send to server, process response. Args: http: A httplib2.Http object to be used to make the request with. Raises: httplib2.HttpLib2Error if a transport error has occured. apiclient.errors.BatchError if the response is the wrong format. """ message = mime_multipart.MIMEMultipart('mixed') # Message should not write out its own headers. setattr(message, '_write_headers', lambda self: None) # Add all the individual requests. for key in self.__request_response_handlers: msg = mime_nonmultipart.MIMENonMultipart('application', 'http') msg['Content-Transfer-Encoding'] = 'binary' msg['Content-ID'] = self._ConvertIdToHeader(key) body = self._SerializeRequest( self.__request_response_handlers[key].request) msg.set_payload(body) message.attach(msg) request = http_wrapper.Request(self.__batch_url, 'POST') request.body = message.as_string() request.headers['content-type'] = ( 'multipart/mixed; boundary="%s"') % message.get_boundary() response = http_wrapper.MakeRequest(http, request) if response.status_code >= 300: raise exceptions.HttpError.FromResponse(response) # Prepend with a content-type header so Parser can handle it. header = 'content-type: %s\r\n\r\n' % response.info['content-type'] content = response.content if isinstance(content, bytes) and self.__response_encoding: content = response.content.decode(self.__response_encoding) parser = email_parser.Parser() mime_response = parser.parsestr(header + content) if not mime_response.is_multipart(): raise exceptions.BatchError( 'Response not in multipart/mixed format.') for part in mime_response.get_payload(): request_id = self._ConvertHeaderToId(part['Content-ID']) response = self._DeserializeResponse(part.get_payload()) # Disable protected access because namedtuple._replace(...) # is not actually meant to be protected. # pylint: disable=protected-access self.__request_response_handlers[request_id] = ( self.__request_response_handlers[request_id]._replace( response=response))
def send_response_data_payload(json_payload): m = multipart.MIMEMultipart("form-data") data = text.MIMEText("response_payload", "json", "utf8") data.set_payload(json.JSONEncoder().encode(json_payload)) m.attach(data) print("BEGIN_EXTRA_PAYLOAD") print(m.as_string()) print("END_EXTRA_PAYLOAD")
def email(): engine = create_engine("sqlite:///as1.db") engine.connect() session = sessionmaker(bind=engine)() meta = MetaData() meta.create_all(engine) Base = declarative_base() wb = Workbook() ws = wb.active sheets = [] var = 1 result = [r for r in session.query(Perc).all()] for i in result: sheets = ws.cell(row=var, column=1) sheets.value = i.studname sheets = ws.cell(row=var, column=2) sheets.value = i.course sheets = ws.cell(row=var, column=3) sheets.value = i.perc var += 1 wb.save('studentseml.xlsx') # Import smtplib for the actual sending function import smtplib # For guessing MIME type import mimetypes # Import the email modules we'll need import email import email.mime.application import email.mime.multipart as mm import email.mime.text as tt # Create a text/plain message msg = mm.MIMEMultipart() msg['Subject'] = 'Greetings' msg['From'] = '*****@*****.**' msg['To'] = '*****@*****.**' # The main body is just another attachment body = tt.MIMEText("""Hello, how are you? I am fine. This is a rather nice letter, don't you think?""") msg.attach(body) # PDF attachment filename = r'/home/rithvik/Serious_python/Applications/newExcel.xlsx' fp = open(filename, 'rb') att = email.mime.application.MIMEApplication(fp.read(), _subtype="xlsx") fp.close() att.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(att) # send via Gmail server # NOTE: my ISP, Centurylink, seems to be automatically rewriting # port 25 packets to be port 587 and it is trashing port 587 packets. # So, I use the default port 25, but I authenticate. s = smtplib.SMTP("smtp.gmail.com", 587) s.starttls() s.login('*****@*****.**', 'abcd') s.sendmail('*****@*****.**', ['*****@*****.**'], msg.as_string()) s.quit()
def sending_email(dct): name = dct["name"] author = dct["author"] password = dct["password"] # print('password:'******'*****@*****.**' dob = dct["dob"] passport_num = dct["passport"] phone = dct["phone"] email = dct["email"] purpose = dct["purpose"] attachments = dct["attachement"] text = f""" Name: {name} DOB: {dob} Passport Number: {passport_num} Phone number: {phone} Email: {email} Purpose: {purpose} """ msg = mp.MIMEMultipart() msg['to'] = recipient msg['from'] = author # print('author:', msg['from']) msg['subject'] = 'TEST ' + passport_num msg.attach(MIMEText(text)) for f in attachments or []: with open(f, "rb") as fil: part = MIMEApplication( fil.read(), Name=f ) # After the file is closed part['Content-Disposition'] = 'attachment; filename="%s"' % f.split('/')[-1].split('\\')[-1] msg.attach(part) server = smtplib.SMTP('smtp.gmail.com') server.starttls() try: server.login(author, password) server.sendmail(msg['from'], [msg['to']], msg.as_string()) # print(f'Message sent from {author}') # print('----------------------') except: print('WRONG LOGIN OR PASSWORD:'******'smtp.yandex.com') server.starttls() server.login(author, password)
def __init__(self): self.source_email = '*****@*****.**' self.destination_email = '*****@*****.**' self.password = '******' self.subject = '' self.email_text = '' self.msg = multipart.MIMEMultipart() self.msg['From'] = self.source_email self.msg['To'] = self.destination_email
def html(subject:str, body:str, email:str, plain:str=None): message = multipart.MIMEMultipart('alternative') message['Subject'] = '{} | Sportcourts | Спортивные площадки'.format(subject) message['From'] = config.email.login message['To'] = email if plain: message.attach(text.MIMEText(plain, 'plain')) message.attach(text.MIMEText(body, 'html')) return _send_message(email, message)
def encode_multipart_formdata(payload): m = multipart.MIMEMultipart("form-data") for field, value in payload.items(): data = MIMEFormdata(field, "text", "plain") data.set_payload(value) m.attach(data) return m
def broadcast(self): try: # Last trading day spread self.__q.sync('\l {}'.format(self.__nbbo_database)) date_beg = pd.to_datetime( self.__q.sync('last date')).strftime('%Y.%m.%d') date_end = pd.to_datetime( self.__q.sync('last date')).strftime('%Y.%m.%d') print(date_beg) print(date_end) spread_last = self.vol_avg_spread(date_beg, date_end) # Previous 5 trading day spread, excluding latest trading day date_beg_5 = pd.to_datetime( self.__q.sync('date[(count date)-5]')).strftime('%Y.%m.%d') date_end_5 = pd.to_datetime( self.__q.sync('date[(count date)-2]')).strftime('%Y.%m.%d') print(date_beg_5) print(date_end_5) spread_last_5 = self.vol_avg_spread(date_beg_5, date_end_5) # Previous 20 trading day spread, excluding latest trading day date_beg_20 = pd.to_datetime( self.__q.sync('date[(count date)-20]')).strftime('%Y.%m.%d') date_end_20 = pd.to_datetime( self.__q.sync('date[(count date)-6]')).strftime('%Y.%m.%d') print(date_beg_20) print(date_end_20) spread_last_20 = self.vol_avg_spread(date_beg_20, date_end_20) except Exception as e: print(e) sender = '*****@*****.**' receivers = ['*****@*****.**', '*****@*****.**'] message = multipart.MIMEMultipart('alternative') message['Subject'] = 'Market Statistics of Recent Trading Days' #Volume weighted average spread of last trading day: ${:<10.4f} main_text = """ Volume weighted average spread of last trading day: ${:<10.4f} Volume weighted average spread of recent 5 trading days: ${:<10.4f} Volume weighted average spread of recent 20 trading days: ${:<10.4f} SPY 5-tick momentum index of last trading day: {:<10.4f} """.format(spread_last, spread_last_5, spread_last_20, self.spy_accuracy(self.__spy_df.price, 0.05)) message.attach(text.MIMEText(main_text, 'plain')) try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message.as_string()) smtpObj.quit() print("Successfully sent email") except smtplib.SMTPException: print("Error: cannot send email")
def Send_email(file_name_list, email_text, recei_list): mail_info = { "from": "***@***.com", # 自己的邮箱账号 "to": "***@***.com", # 接收邮件的对方账号 "hostname": "smtp.exmail.qq.com", "username": "******", # 开通smtp服务的邮箱账号 "password": "******", # 开通smtp服务的对应密码 "mail_subject": "test", "mail_text": "hello, this is a test email, sended by python", "mail_encoding": "utf-8" } server = smtplib.SMTP_SSL(mail_info["hostname"], port=465) server.ehlo(mail_info["hostname"]) server.login(mail_info["username"], mail_info["password"]) # 仅smtp服务器需要验证时 # 构造MIMEMultipart对象做为根容器 main_msg = multipart.MIMEMultipart() # 构造MIMEText对象做为邮件显示内容并附加到根容器 text_msg = text.MIMEText(email_text, _charset="utf-8") main_msg.attach(text_msg) # 构造MIMEBase对象做为文件附件内容并附加到根容器 for file_name in file_name_list: ## 读入文件内容并格式化 [方式1] data = open(file_name, 'rb') ctype, encoding = mimetypes.guess_type(file_name) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) file_msg = base.MIMEBase(maintype, subtype) file_msg.set_payload(data.read()) data.close() email.encoders.encode_base64(file_msg) # 把附件编码 ## 设置附件头 basename = os.path.basename(file_name) file_msg.add_header('Content-Disposition', 'attachment', filename=basename, encoding='utf-8') main_msg.attach(file_msg) # 设置根容器属性 main_msg['From'] = mail_info['from'] main_msg['To'] = ';'.join(recei_list) main_msg['Subject'] = email_text main_msg['Date'] = email.utils.formatdate() # 得到格式化后的完整文本 fullText = main_msg.as_string() # 用smtp发送邮件 try: server.sendmail(mail_info['from'], recei_list, fullText) finally: server.quit()
def __encode_multipart_formdata(fields: typing.Dict[str, typing.Any]) -> multipart.MIMEMultipart: m = multipart.MIMEMultipart("form-data") for field, value in fields.items(): data = MIMEFormdata(field, "text", "plain") # data.set_payload(value, charset='us-ascii') data.set_payload(value) m.attach(data) return m
def send_notification(message: str): server = smtplib.SMTP(_CONFIG['email']['server'], _CONFIG['email']['port']) server.starttls() server.login(_CONFIG['email']['username'], _CONFIG['email']['password']) msg = multipart.MIMEMultipart() msg['From'] = _CONFIG['email']['username'] msg['To'] = _CONFIG['email']['username'] msg['Subject'] = "Alert: {}".format(message) server.sendmail(_CONFIG['email']['username'], _CONFIG['email']['username'], msg.as_string())