def mandaEmail(): print(' ') hoje = date.today() msg = MIMEMultipart() msg['Subject'] = "Check Troughput - " + str(hoje.day) + "/" + str( hoje.month) + "/" + str(hoje.year) msg.attach(MIMEText('Prezados, segue check de troughput')) part = MIMEBase('application', 'octect-stream') part.set_payload( open( os.path.join('/home/user/Documentos/SCRIPTS/troughput/equissel/', 'salvatroughput.xlsx'), 'rb').read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="salvatroughput.xlsx"') msg.attach(part) smtpObj = smtplib.SMTP('smtp.gmail.com', 587) print('Aguardando resposta do server...') print('') print(smtpObj.ehlo()) # resposta do server print('') print('Aguardando status tls do server...') print('') print(smtpObj.starttls()) # status do TLS print('') print('Enviando credenciais de acesso...') print(smtpObj.login('*****@*****.**', 'senhaemailenvioautomatico')) # login print('') print('OK! Mandando email...') smtpObj.sendmail( '*****@*****.**', ['*****@*****.**', '*****@*****.**'], msg.as_string()) print('Fechando conexao...') print(smtpObj.quit()) print('') print('Email enviado!')
def send_mail(self, output_file, output_dir): try: msg = MIMEMultipart() msg['From'] = self.from_mail msg['To'] = self.to_mail msg['Subject'] = self.subject body = self.message msg.attach(MIMEText(body, 'plain')) filename = output_file attachment = open(output_dir, "rb") part = MIMEBase('application', 'octet-stream') part.set_payload(attachment.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % filename) msg.attach(part) smtp = smtplib.SMTP_SSL(self.smtp_host, self.smtp_port) smtp.ehlo() smtp.login(self.from_mail, self.smtp_password_temp) text = msg.as_string() smtp.sendmail(self.from_mail, self.to_mail, text) smtp.close() self.log.info("message sent successfully") except: self.log.info("message sending failed")
def send_mail(from_user, pwd, to_user, cc_users, subject, text, attach): COMMASPACE = ", " msg = MIMEMultipart("alternative") #msg = MIMEMultipart() msg["From"] = from_user msg["To"] = to_user msg["Cc"] = COMMASPACE.join(cc_users) msg["Subject"] = Header(s=subject, charset="utf-8") msg["Date"] = Utils.formatdate(localtime=1) msg.attach(MIMEText(text, "html", _charset="utf-8")) if (attach != None): part = MIMEBase("application", "octet-stream") part.set_payload(open(attach, "rb").read()) Encoders.encode_base64(part) part.add_header( "Content-Disposition", "attachment; filename=\"%s\"" % os.path.basename(attach)) msg.attach(part) smtp_server = "smtp.gmail.com" port = 587 smtp = smtplib.SMTP(smtp_server, port) smtp.starttls() smtp.login(from_user, pwd) print "gmail login OK!" smtp.sendmail(from_user, cc_users, msg.as_string()) print "mail Send OK!" smtp.close()
def send_report(from_addr, to_addr, msg, passes, failures): to_send = MIMEMultipart() to_send['From'] = "DMARC forwarder bot <%s>" % patch_email(from_addr) to_send['To'] = patch_email(to_addr) to_send['Subject'] = msg['Subject'] bodytext = "Received %u correct emails.\n" % sum(passes.values()) for host in failures: hostname, _, _ = socket.gethostbyaddr(host) bodytext += "Received %u failures from %s (%s)" % (failures[host], host, hostname) if host in passes: bodytext += " (also received %u correct ones)" % passes[host] bodytext += "\n" to_send.attach(MIMEText(bodytext, "plain")) zippart = get_zippart(msg) attachment = MIMEBase('application', 'zip') attachment.set_payload(zippart.get_payload(decode=True)) email.encoders.encode_base64(attachment) attachment.add_header('Content-disposition', 'attachment', filename=zippart.get_filename()) to_send.attach(attachment) with smtplib.SMTP('localhost') as s: s.send_message(to_send)
def __build_file_msg(self, file_list): if file_list: for file_path in file_list: # 构造MIMEBase对象做为文件附件内容并附加到根容器 contype = 'application/octet-stream' maintype, subtype = contype.split('/', 1) ## 读入文件内容并格式化 try: data = open(file_path, 'rb') except Exception as e: return file_msg = MIMEBase(maintype, subtype) file_msg.set_payload(data.read()) email.Encoders.encode_base64(file_msg) ## 设置附件头 basename = os.path.basename(file_path) file_msg.add_header('Content-Disposition', 'attachment', filename=basename) self.main_msg.attach(file_msg) else: pass
def send_mail(test_module): from_addr = CONFIG['FROM'] password = CONFIG['PASSWORD'] smtp_server = CONFIG['SMTP'] to_addr = CONFIG['TO'] # Email object msg = MIMEMultipart() msg['From'] = _format_add(u"OSPerformance<%s>" % from_addr) msg['To'] = _format_add(u"Tester<%s>" % to_addr) msg['Subject'] = Header(u"OSPerformance test finish... %s" % test_module, "utf-8").encode() # Email body msg.attach( MIMEText(test_module + ' Test finished. \nResult please refer to the attachment')) # Email attachment with open('E:/Automation/square-compat.xml', 'rb') as f: mime = MIMEBase('xml', 'xml', filename='test.xml') mime.add_header('Content-Disposition', 'attachment', filename='test.xml') mime.add_header('Content-ID', '<0>') mime.add_header('X-Attachment-ID', '0') mime.set_payload(f.read()) encoders.encode_base64(mime) msg.attach(mime) server = smtplib.SMTP(smtp_server, 25) server.set_debuglevel(1) server.login(from_addr, password) server.sendmail(from_addr, [to_addr], msg.as_string()) server.quit()
def email(text, subject=None, attach=None): """Send email with with attachments. If subject is None, the default will be used.""" if email_options['emlusr'] != '' and email_options[ 'emlpwd'] != '' and email_options['emladr'] != '': gmail_user = email_options['emlusr'] # User name gmail_name = options.name # OSPi name gmail_pwd = email_options['emlpwd'] # User password # -------------- msg = MIMEMultipart() msg['From'] = gmail_name msg['To'] = email_options['emladr'] msg['Subject'] = subject or email_options['emlsubject'] msg.attach(MIMEText(text)) if attach is not None and os.path.isfile(attach) and os.access( attach, os.R_OK): # If insert attachments part = MIMEBase('application', 'octet-stream') part.set_payload(open(attach, 'rb').read()) encode_base64(part) part.add_header( 'Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attach)) msg.attach(part) mail_server = smtplib.SMTP("smtp.gmail.com", 587) mail_server.ehlo() mail_server.starttls() mail_server.ehlo() mail_server.login(gmail_user, gmail_pwd) mail_server.sendmail( gmail_name, email_options['emladr'], msg.as_string()) # name + e-mail address in the From: field mail_server.close() else: raise Exception('E-mail plug-in is not properly configured!')
def send_msg(self, to, subject, body, attachments = None): if attachments: msg = MIMEMultipart() msg.attach(MIMEText( body)) else: msg = MIMEText(body) msg['To'] = to msg['From'] = self.__username msg['Subject'] = subject if attachments: for path in attachments: if not os.path.exists(path): break content_type, encoding = mimetypes.guess_type(path) if content_type is None or encoding is not None: content_type = 'application/octet-stream' main_type, subtype = content_type.split('/', 1) with open(path, 'rb') as file: data = file.read() attachment = MIMEBase(main_type, subtype) attachment.set_payload(data) email.encoders.encode_base64(attachment) attachment.add_header('Content-Disposition', 'attachment', filename = os.path.basename(path)) msg.attach(attachment) status = self.smtp.sendmail(self.__username, to, msg.as_string()) return status
def SendGmail(subject, message, to=None, attach=None): gmail_username = GetTheConfig('google', 'gmail_username') # email User gmail_user = GetTheConfig('google', 'gmail_user') # email Address gmail_pwd = GetTheConfig('google', 'gmail_pwd') # email password msg = MIMEMultipart('alternative') if not to == None: msg['To'] = to else: msg['To'] = gmail_user to = gmail_user msg['From'] = gmail_username msg['Subject'] = Header(subject, 'utf-8') # 제목 msg.attach(MIMEText(message, 'plain', 'utf-8')) # 내용이 평문일 경우 #msg.attach(MIMEText(message, 'html', 'utf-8')) # 내용이 html일 경우 if not attach == None: # 첨부파일이 존재하는 경우 - 일반 글 배포 외 다른 용도로 사용 시 part = MIMEBase('application', 'octet-stream') part.set_payload(open(attach, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attach)) msg.attach(part) mailServer = smtplib.SMTP("smtp.gmail.com", 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(gmail_user, gmail_pwd) mailServer.sendmail(gmail_user, to, msg.as_string()) mailServer.close()
def send_email(from_addr, pwd, to_addr, subject, pics_path): msg = MIMEMultipart() msg['From'] = _format_addr('<%s>' % from_addr) msg['To'] = _format_addr('<%s>' % to_addr) msg['Subject'] = Header(subject, 'utf-8').encode() msg.attach(MIMEText('Text', 'plain', 'utf-8')) for pic in pics_path: pic_name = pic.split('/')[1] print("Adding %s to attachment" % pic_name) with open(pic, 'rb') as f: mime = MIMEBase('image', 'png', filename=pic_name) mime.add_header('Content-Disposition', 'attachment', filename=pic_name) mime.add_header('Content-ID', '<0>') mime.add_header('X-Attachment-Id', '0') mime.set_payload(f.read()) encoders.encode_base64(mime) msg.attach(mime) smtp_server = 'owa.zingsemi.com' server = smtplib.SMTP(smtp_server, 25) server.set_debuglevel(1) server.login(from_addr, pwd) server.sendmail(from_addr, [to_addr], msg) server.quit()
def mail(mail_to, subject, text, file): """send email""" mailserver = smtplib.SMTP("smtp.gmail.com", 587) mailserver.starttls() mailserver.ehlo() mailserver.login(cred.get('GMAIL','USER'), cred['GMAIL']['PASSWD']) msg = MIMEMultipart() text_msg = MIMEText(text, "html") msg.attach(text_msg) contype = 'application/octet-stream' maintype, subtype = contype.split('/', 1) data = open(file, 'rb') file_msg = MIMEBase(maintype, subtype) file_msg.set_payload(data.read()) data.close() email.Encoders.encode_base64(file_msg) basename = os.path.basename(file) file_msg.add_header('Content-Disposition', 'attachment', filename=basename) msg.attach(file_msg) msg['Date'] = email.Utils.formatdate() msg['From'] = "*****@*****.**" msg['Subject'] = subject mailserver.sendmail(cred.get('GMAIL', 'USER'), mail_to, msg.as_string()) mailserver.close()
def send_email(filename, email): with open(filename, "rb") as fp: attachment = fp.read() body = MIMEText(MESSAGE_TEMPLATE) # Compose attachment part = MIMEBase('application', "octet-stream") part.set_payload(attachment) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % filename) # Compose message msg = MIMEMultipart() msg["Subject"] = MESSAGE_SUBJECT msg["From"] = CURATOR_EMAIL msg["To"] = email msg.attach(part) msg.attach(body) # Establish connection server = smtplib.SMTP_SSL() server_addres = CURATOR_EMAIL.split("@")[1] server.connect('smtp.%s' % server_addres) server.login(CURATOR_EMAIL, CURATOR_PASS) # Send mail server.sendmail(msg["From"], msg["To"], msg.as_string()) server.quit() print("Mail to {} sent".format(email))
def sendMsgWithImage(from_addr, to_addr): """ 发送正文带有图片的邮件 :return: """ msg = MIMEMultipart() msg['From'] = _format_addr('Python爱好者 <%s>' % from_addr) msg['To'] = _format_addr('管理员 <%s>' % to_addr) msg['Subject'] = Header('来自SMTP的问候……', 'utf-8').encode() # 邮件正文是MIMEText: msg.attach( MIMEText( '<html><body><h1>Hello</h1>' + '<p><img src="cid:0"></p>' + '</body></html>', 'html', 'utf-8')) # 添加附件就是加上一个MIMEBase,从本地读取一个图片: with open('../../../static/images/heben.jpg', 'rb') as f: # 设置附件的MIME和文件名,这里是png类型: mime = MIMEBase('image', 'png', filename='heben.jpg') # 加上必要的头信息: mime.add_header('Content-Disposition', 'attachment', filename='test.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) return msg
def sendmail(body, fromaddr, toaddr, mypass, filename): msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "[Test] Entity differences" msg.attach(MIMEText(body, 'plain')) if os.path.exists(filename) and os.path.isfile(filename): with open(filename, 'rb') as file: attachment = MIMEBase('application', "octet-stream") attachment.set_payload(file.read()) email.encoders.encode_base64(attachment) nameAttach = Header(os.path.basename(filename), 'utf-8') attachment.add_header('Content-Disposition', 'attachment; filename="%s"' % nameAttach) msg.attach(attachment) else: if filename.lstrip() != "": print("File for attach not found - " + filename) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(fromaddr, mypass) text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit()
def send_mail_with_attach(self, from_addr, to_addr, subject, content): # 邮件对象: msg = MIMEMultipart() from_addr = 'Python爱好者<%s>' % from_addr to_addr = '管理员<%s>' % to_addr msg['From'] = self._format_addr('Python爱好者<*****@*****.**>') msg['To'] = self._format_addr(to_addr) msg['Subject'] = Header(subject, 'utf-8').encode() # 邮件正文是MIMEText: msg.attach(MIMEText(content, 'plain', 'utf-8')) # 添加附件就是加上一个MIMEBase,从本地读取一个图片: with open('/home/wfq/ops/static/image/qicheng.jpg', 'rb') as f: # 设置附件的MIME和文件名,这里是png类型: mime = MIMEBase('image', 'jpg', filename='qicheng.jpg') # 加上必要的头信息: mime.add_header('Content-Disposition', 'attachment', filename='qicheng.jpg') 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) server = self._get_smtp_server() server.sendmail(from_addr, [to_addr], msg.as_string()) server.quit() return ''
def send_email(filename, email): with open(filename, "rb") as fp: attachment = fp.read() with open("msg_body", encoding="utf-8") as fp: body = MIMEText(fp.read(), "plain") with open("auth", "r") as fp: login, password = fp.read().split() # Compose attachment part = MIMEBase('application', "octet-stream") part.set_payload(attachment) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % filename) # Compose message msg = MIMEMultipart() msg["Subject"] = "Фоксфорд. Еженедельный отчёт" msg["From"] = login msg["To"] = email msg.attach(part) msg.attach(body) # Establish connection server = smtplib.SMTP_SSL() server_addres = login.split("@")[1] server.connect('smtp.%s' % server_addres) server.login(login, password) # Send mail server.sendmail(msg["From"], msg["To"], msg.as_string()) server.quit() print("Mail to {} sent".format(email))
def MessageAllInc(mess, namefile): fromadr = "*****@*****.**" toadr = ["*****@*****.**", "*****@*****.**"] toadrs = "*****@*****.**>" mail_coding = 'utf-8' outs = mess part = MIMEBase('application', "octet-stream") part.set_payload(open(namefile, "rb").read()) basename = os.path.basename(namefile) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % basename) message = MIMEMultipart('related') message['Subject'] = Header("subject mail", mail_coding) message['From'] = Header(fromadr, mail_coding) message['To'] = Header(toadrs, mail_coding) msg = MIMEText(outs.encode(mail_coding), 'plain', mail_coding) msg.set_charset(mail_coding) message.attach(msg) message.attach(part) s = smtplib.SMTP(host) s.sendmail(fromadr, toadr, message.as_string()) s.quit()
def mysendmail(self, send_file=False, test_type='plain'): # 配置邮件正文 if send_file: self.msg = MIMEMultipart() with open('', 'rb') as f: mime = MIMEBase('image', 'png', filename=self.file_name) mime.add_header('Content-Disposition', 'attachment', filename='test.png') mime.add_header('Content-ID', '<0>') mime.add_header('X-Attachment-Id', '0') mime.set_payload(f.read()) encoders.encode_base64(mime) self.msg.attach(mime) else: self.msg = MIMEText(self.message, test_type, 'utf-8') # 配置邮件发送这及显示名称 self.msg['From'] = self._format_addr(u'%s <%s>' % (self.from_name, self.from_addr)) # 配置邮件接受这及显示名称 # msg['To']接受的是字符串而不是list,如果有多个邮件地址,用,分隔即可 self.msg['To'] = self._format_addr(u'%s <%s>' % (self.to_name, self.to_addr)) # 配置邮件主题 self.msg['Subject'] = Header(u'%s' % self.subject, 'utf-8').encode() # 发送电子邮件 self.server = smtplib.SMTP() self.server.connect(self.smtp_server, 25) self.server.login(self.from_addr, self.mail_pass) self.server.sendmail(self.from_addr, [self.to_addr], self.msg.as_string()) self.server.quit()
def get_attach_msg(from_addr, to_addr): # 邮件对象: msg = MIMEMultipart() msg['From'] = _format_addr('Python爱好者 <%s>' % from_addr) msg['To'] = _format_addr('管理员 <%s>' % to_addr) msg['Subject'] = Header('来自SMTP的问候……', 'utf-8').encode() # 邮件正文是MIMEText。文本plain和网页HTML可以同时存在。 msg.attach(MIMEText('send with file...', 'plain', 'utf-8')) #这个是带附件的text邮件 # msg.attach(MIMEText('<html><body><h1>Hello</h1>' + # '<p><img src="cid:0"></p>' + # '</body></html>', 'html', 'utf-8'))#这个是带附件的HTML邮件,可以把附件的图片放到邮件正文中。 # 添加附件就是加上一个MIMEBase,从本地读取一个图片: with open('/Users/apple/Pictures/111.png', 'rb') as f: # 设置附件的MIME和文件名,这里是png类型: mime = MIMEBase('image', 'png', filename='test.png') # 加上必要的头信息: mime.add_header('Content-Disposition', 'attachment', filename='test.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) return msg
def multipart_format(parts): """Make a multipart message Args: parts: list of (content_type, data) tuples Returns: (headers, data) tuple """ multi_message = MIMEMultipart('related') for content_type, data in parts: msg = MIMEBase(*content_type.split('/', 1)) msg.set_payload(data) multi_message.attach(msg) body_lines = [] in_headers = True last_key = None headers = {} for line in multi_message.as_string().splitlines(True): if in_headers: if line == '\n': in_headers = False elif line.startswith(' ') and last_key: headers[last_key] += line.rstrip() else: key, value = line[:-1].split(':') headers[key] = value.strip() last_key = key else: body_lines.append(line) return headers, ''.join(body_lines)
def email_sender(): #This is a path that pictures were capture there. #we need that path to find and email pictures files = os.listdir("/home/pi/Desktop") extension = "jpg" for file in files: if extension in file: #code just find the file with .jpg extention in the path we have user ="******" #sending gmail recv ="*****@*****.**" #receiving gmail subject = "Someone enter to Your room" #subject of email message message = MIMEMultipart() message["From"] = user message["To"] = recv message["Subject"]= subject #titel of email set here. body = "This person enter your room!!" message.attach(MIMEText(body,"plain")) attachment = open(file,"rb") part = MIMEBase("application","octet-stream") part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header("Content-Disposition","attachment;filename= " + file) #Attach the massge now. message.attach(part) text = message.as_string() #587 SMTP port is for emails server = smtplib.SMTP("smtp.gmail.com",587) server.starttls() server.login(user,"********") server.sendmail(user,recv,text) server.quit() else: pass
def send_email_file(self, to_addrs, msg_text, file_path, subject_test='来自SMTP的问候'): # 邮件对象 msg = MIMEMultipart('alternative') # 邮件正文是MIMEText: msg.attach(MIMEText(msg_text, 'plain', 'utf-8')) with open(file_path, 'rb') as f: # 设置附件和MIME,从本地读取一个图片 mime = MIMEBase('image', 'jpeg', filename=file_path.split('/')[-1]) # 加上必要的头信息: mime.add_header('Content-Disposition', 'attachment', filename=file_path.split('/')[-1]) 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) return self.send_email_base(to_addrs, msg, subject_test)
def send_mail(self, status): # status: 'err' or 'done' self.grab((0, 0, 1, 1), 'final_shot') with open(ROOT + 'data/fgo.LOG', 'r') as f: res = f.readlines() res = [x.replace('<', '<').replace('>', '>') for x in res] res = ''.join([x[:-1] + '<br />' for x in res]) msg = MIMEMultipart() with open(ROOT + 'data/final_shot.png', 'rb') as f: mime = MIMEBase('image', 'jpg', filename='shot.png') mime.add_header('Content-Disposition', 'attachment', filename='shot.png') mime.add_header('Content-ID', '<0>') mime.add_header('X-Attachment-Id', '0') mime.set_payload(f.read()) encoders.encode_base64(mime) msg.attach(mime) msg.attach(MIMEText('<html><body><p><img src="cid:0"></p>' + '<font size=\"1\">{}</font>'.format(res) + '</body></html>', 'html', 'utf-8')) msg['From'] = Header('why酱のFGO脚本', 'utf-8') msg['Subject'] = Header( '[FGO] - Status: {}, {}'.format(status, time.strftime('%m-%d%H:%M')), 'utf-8') server = smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT) try: server.ehlo() # server.starttls() server.login(FROM_ADDRESS, PASSWD) server.sendmail(FROM_ADDRESS, [TO_ADDRESS], msg.as_string()) server.quit() print('➜ Mail sent successfully. Please check it.') except Exception as e: print('\nError type: ', e) print('➜ Mail sent failed. Maybe there are something wrong.')
def sendMessage(self, fpath, folder): try: fname = ntpath.basename(fpath) Logs.Print("Sending email for " + folder + " and file: " + str(fname)) msg = MIMEMultipart() msg['Subject'] = "ALARM DETECTED ON " + folder msg['From'] = "ALERT! " + "<" + self.mail_from + ">" msg['To'] = self.mail_to part = MIMEBase('application', "octet-stream") part.set_payload(open(fpath, "rb").read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="' + fname + '"') msg.attach(part) server = SMTP(self.smtp_server, timeout=10) server.set_debuglevel(0) #server.login(self.username, self.password) server.sendmail(msg['From'], msg['To'], msg.as_string()) Logs.Print('Message sent') except Exception as e: Logs.Print("Exception: " + str(e)) finally: if server: server.quit()
def newMail(mail_from, mail_to, mail_subj, mail_text, attach_list=[], mail_coding='utf-8'): """формирование сообщения""" multi_msg = MIMEMultipart() multi_msg['From'] = Header(mail_from, mail_coding) multi_msg['To'] = Header(mail_to, mail_coding) multi_msg['Subject'] = Header(mail_subj, mail_coding) msg = MIMEText(mail_text.encode('utf-8'), 'plain', mail_coding) msg.set_charset(mail_coding) multi_msg.attach(msg) # присоединяем атач-файл for _file in attach_list: if exists(_file) and isfile(_file): with open(_file, 'rb') as fl: attachment = MIMEBase('application', "octet-stream") attachment.set_payload(fl.read()) email.encoders.encode_base64(attachment) only_name_attach = Header(basename(_file), mail_coding) attachment.add_header('Content-Disposition',\ 'attachment; filename="%s"' % only_name_attach) multi_msg.attach(attachment) else: if(attach_file.lstrip() != ""): print("Файл для атача не найден - %s" %_file) return multi_msg
def send_HTML_Double_Attachment_Mail(self, To_Add, Subject, htmlMessage, path1, filename1, path2, filename2): try: Mail_Body = self.initialise_Mail_Body(To_Add, Subject) #Attach Mail Message Mail_Msg = MIMEText(htmlMessage, 'html') attachment1 = open(path1, "rb") Mail_Attachment1 = MIMEBase('application', 'octet-stream') Mail_Attachment1.set_payload((attachment1).read()) encoders.encode_base64(Mail_Attachment1) Mail_Attachment1.add_header('Content-Disposition', "attachment; filename= %s" % filename1) attachment2 = open(path2, "rb") Mail_Attachment2 = MIMEBase('application', 'octet-stream') Mail_Attachment2.set_payload((attachment2).read()) encoders.encode_base64(Mail_Attachment2) Mail_Attachment2.add_header('Content-Disposition', "attachment; filename= %s" % filename2) Mail_Body.attach(Mail_Msg) Mail_Body.attach(Mail_Attachment1) Mail_Body.attach(Mail_Attachment2) #Send Mail self.session.sendmail(FROM_ADD, [To_Add], Mail_Body.as_string()) except: pass
def smtp(self): server = smtplib.SMTP_SSL(smtpServer, smtpServer_host) server.set_debuglevel(1) server.login(address, password) content = """ 执行测试中.... 测试已完成!!! 生成报告中.... 报告已生成.... 报告已邮件发送!!! """ msg = MIMEMultipart() msg["From"] = self.__format__addr("%s" % address) msg["To"] = self.__format__addr("%s" % toAddress) msg["Subject"] = Header("测试报告", "utf-8").encode() msg.attach(MIMEText(content, "plain", "utf-8")) with open(mail_path, "rb") as f: mime = MIMEBase("file", "html", filename="test.html") mime.add_header("Content-Disposition", "attachment", filename="test.html") 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) server.sendmail(address, [toAddress], msg.as_string()) server.quit()
def getAttachment(attachmentFilePath): contentType, encoding = mimetypes.guess_type(attachmentFilePath) if contentType is None or encoding is not None: contentType = 'application/octet-stream' mainType, subType = contentType.split('/', 1) file = open(attachmentFilePath, 'rb') if mainType == 'text': attachment = MIMEBase(mainType, subType) attachment.set_payload(file.read()) encode_base64(attachment) elif mainType == 'image': attachment = MIMEImage(file.read()) else: attachment = MIMEBase(mainType, subType) attachment.set_payload(file.read()) encode_base64(attachment) file.close() attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachmentFilePath)) return attachment
def send_mail(subject, content, image=None): server = _smtp_server() if not server: return False msg = MIMEMultipart() msg['From'] = formataddr((Header('Auto Shipper', 'utf8').encode(), _from_email)) msg['Subject'] = Header(subject, 'utf8').encode() if image: image.thumbnail((1000, 1000)) image.save('tmp/thumbnail.png') with open('tmp/thumbnail.png', 'rb') as file: msg_image = MIMEBase('image', 'png', filename='attachment.png') msg_image.add_header('Content-Disposition', 'attachment', filename='attachment.png') msg_image.add_header('Content-ID', '<0>') msg_image.add_header('X-Attachment-Id', '0') msg_image.set_payload(file.read()) encoders.encode_base64(msg_image) msg.attach(msg_image) content += '<p><img src="cid:0"></p>' msg.attach(MIMEText(content, 'html', 'utf8')) server.sendmail(_from_email, _to_email, msg.as_string()) server.quit() return True
def _send(subject, mail_from, rcpt_to, body, filename): root_message = MIMEMultipart() root_message["Subject"] = smtplib.email.Header.Header(subject, "utf-8") root_message["From"] = mail_from root_message["To"] = rcpt_to root_message["Date"] = formatdate() # 本文 message = MIMEText(body) message.add_header("Content-Type", "text/plain; charset=UTF-8") root_message.attach(message) # 添付ファイル attachment = MIMEBase("text", "") attachment_body = _read_text_file(filename) attachment.set_payload(attachment_body) encoders.encode_base64(attachment) attachment.add_header("Content-Disposition", "attachment", filename=filename) root_message.attach(attachment) s = smtplib.SMTP("127.0.0.1:25") composed = root_message.as_string() s.sendmail(mail_from, [rcpt_to], composed) s.close()
def send_mail(from_user, pwd, to_user, cc_users, subject, text, attach): COMMASPACE = ", " msg = MIMEMultipart("alternative") #msg = MIMEMultipart() msg["From"] = from_user msg["To"] = to_user msg["Cc"] = COMMASPACE.join(cc_users) msg["Subject"] = Header(s=subject, charset="utf-8") msg["Date"] = Utils.formatdate(localtime = 1) msg.attach(MIMEText(text, "html", _charset="utf-8")) if (attach != None): part = MIMEBase("application", "octet-stream") part.set_payload(open(attach, "rb").read()) Encoders.encode_base64(part) part.add_header("Content-Disposition", "attachment; filename=\"%s\"" % os.path.basename(attach)) msg.attach(part) smtp_server = "smtp.gmail.com" port = 587 smtp = smtplib.SMTP(smtp_server, port) smtp.starttls() smtp.login(from_user, pwd) print "gmail login OK!" smtp.sendmail(from_user, cc_users, msg.as_string()) print "mail Send OK!" smtp.close()
def send_mail(self, to, subject, body, attachments=[], full_attachments={}): '''Sends a message to the given recipient, attachments is a list of file paths to attach, they will be attached with the given names, and if there is a problem they won't be attached and the message will still be sent. PARAMATERS: to - Email address to send the message to. (String) subject - Subject of the email (String) body - Body of the email (html allowed) (String) attachments - A list of attachments to the message. full_attachments - A dict of things to attach, name => data. each name should be unique. Raises a NotConfiguredException if smtp has not yet been set up. ''' if not self._smtp_configured: raise NotConfiguredException, "SMTP is not configured." # Setup the message msg = MIMEMultipart() msg['From'] = self.smtp_username msg['To'] = to msg['Subject'] = subject # Attach the body. msg.attach(MIMEText(body, 'html')) # Attach each attachment. for attach in attachments: with open(attach, 'rb') as o: part = MIMEBase('application', 'octet-stream') part.set_payload(o.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attach)) msg.attach(part) # Attach everything from the full attachments dictionary. for name in full_attachments.keys(): part = MIMEBase('application', 'octet-stream') part.set_payload(full_attachments[name]) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % (name)) msg.attach(part) # Beam me up Scotty! mailServer = smtplib.SMTP(self.smtp_url, self.smtp_port) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(self.smtp_username, self.smtp_password) mailServer.sendmail(self.smtp_username, to, msg.as_string()) mailServer.close() if DEBUG: print ("%s - Message sent to: %s" % (time.strftime("%Y-%m-%d %H:%M:%S"), to))
def prepare_attachment(self, attachment_path): attachment = MIMEBase("application", "octet-stream") attachment.set_payload(open(attachment_path, "rb").read()) encode_base64(attachment) attachment.add_header( "Content-Disposition", f'attachment; filename="{attachment_path.name}"') return attachment
def send(name): """发送邮件""" # 配置邮件信息 message = MIMEMultipart() message['Cc'] = ",".join(ACC) date = time.strftime("%Y%m%d", time.localtime()) subject = "日报-{}-{}".format(USER_NAME, date) message['Subject'] = subject message['From'] = SENDER message['To'] = RECEIVE[0] # 构造附件 1 # att = MIMEText(open(name, 'rb').read(), 'base64', 'utf-8') # att["Content-Type"] = 'application/octet-stream' # # att['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' # # 这里的filename可以任意写,写什么名字,邮件中显示什么名字 # att["Content-Disposition"] = 'attachment; filename="'+str(name.encode("gb2312"))+'"' # message.attach(att) # 构造附件 2 解决附件名有中文问题 att = MIMEBase('application', 'octet-stream') att.set_payload(open(name, 'rb').read()) att.add_header('Content-Disposition', 'attachment', filename=('gbk', '', name)) encoders.encode_base64(att) message.attach(att) while True: try: # 邮件发送 目前只支持qq和163 if "163" in MAIL_HOST: smtp_obj = smtplib.SMTP() elif "qq" in MAIL_HOST: smtp_obj = smtplib.SMTP_SSL(MAIL_HOST, MAIL_PORT) # 启用SSL发信 else: print("Error: 没有改邮箱主机") os.remove(name) sys.exit() if "163" in MAIL_HOST: smtp_obj.connect(MAIL_HOST, port=MAIL_PORT) smtp_obj.login(SENDER, MALL_PASS) # 登录验证 smtp_obj.sendmail(SENDER, RECEIVE+ACC , message.as_string()) # 发送 print("邮件发送成功 ^_^") smtp_obj.quit() break except smtplib.SMTPException as e: print("Error:邮件发送失败 @_@") print(e) r = input("重新发送?(Y/n):") while r != 'Y' and r != 'y' and r != 'N' and r != 'n': r = input("请输入Y或者n(不区分大小写):") if r == "Y" or r == "y": print("正在重新发送。。。") else: print("取消重新发送。。。") break
def notificate(self, subject, message=None, files=None): """notificate. Args: subject:subject of email. message:message of email. files:file attacment. """ # read to_addr and to_name from notificate.ini config = readconfig() if not config: print('Not valid configure\n') return from_addr = config.from_addr from_name = config.from_name user = config.email_user password = config.email_password smtp_server = config.email_server smtp_port = config.email_port msg = MIMEMultipart() msg['From'] = _format_addr('%s <%s>' % (from_name, from_addr)) msg['To'] = ', '.join([ _format_addr('%s <%s>' % (to_name, to_addr)) for to_addr, to_name in zip(config.addr, config.name) ]) msg['Subject'] = Header(subject, 'utf-8').encode() if message: msg.attach(MIMEText('%s' % message, 'plain', 'utf-8')) if files: for filepath in files: with open(filepath, 'rb') as f: part = MIMEBase('application', 'octet-stream') part.add_header('Content-Disposition', 'attacment', filename=os.path.basename(filepath)) part.set_payload(f.read()) encoders.encode_base64(part) msg.attach(part) while True: try: server = smtplib.SMTP(smtp_server, smtp_port) server.starttls() server.login(user, password) server.sendmail(from_addr, config.addr, msg.as_string()) server.quit() now = str(datetime.datetime.now().replace(second=0, microsecond=0)) for to_addr in config.addr: print('%s: Send email to %s successfully!\n' % (now, to_addr)) except: raise time.sleep(300) else: break
def mail_send_service(from_addr, password, to_addr, content=None, smtp_sever='smtp.qq.com', content_type='plain', filepath=[]): #用于构造邮件的from、to以及subject def _format_addr(s): name, addr = parseaddr(s) return formataddr((Header(name, 'utf-8').encode(), addr)) #发送方账号、密码 from_add = from_addr password = password #接收方账号密码 to_addr = to_addr #smtp服务器地址 smtp_sever = smtp_sever #构造邮件正文及发送人、接收人、主题格式 msg = MIMEMultipart() msg.attach(MIMEText(content, content_type, 'utf-8')) # 为邮件添加附件 if filepath: for path, num in zip(filepath, range(len(filepath))): filetype = path.split('.')[-1] filename = path.split('\\')[-1] with open(path, 'rb') as f: mime = MIMEBase(None, filetype, filename=filename) #加上必要的头信息 mime.add_header('Content-Disposition', 'attachment', filename=filename) mime.add_header('Content-ID', '<%s>' % num) mime.add_header('X-Attachment-Id', '<%s>' % num) #把附件内容读进来 mime.set_payload(f.read()) #使用base_64进行编码 encoders.encode_base64(mime) #添加到MIMEMultipart msg.attach(mime) #邮件from、to、object显示内容,可以自行修改 msg['From'] = _format_addr('Think<%s>' % from_add) msg['To'] = _format_addr('You<%s>' % to_addr) msg['Subject'] = Header('Thinking...', 'utf-8').encode() #执行操作,QQ服务器是通过SSL进行信息传输的 sever = smtplib.SMTP_SSL('smtp.qq.com', 465) # sever.set_debuglevel(1) sever.login(from_add, password) sever.sendmail(from_add, [to_addr], msg.as_string()) sever.quit()
def notificate(self, subject, message=None, files=None): """notificate. Args: subject:subject of email. message:message of email. files:file attacment. """ # read to_addr and to_name from notificate.ini config = readconfig() if not config: print('Not valid configure\n') return from_addr = config.from_addr from_name = config.from_name user = config.email_user password = config.email_password smtp_server = config.email_server smtp_port = config.email_port msg = MIMEMultipart() msg['From'] = _format_addr('%s <%s>' % (from_name, from_addr)) msg['To'] = ', '.join([ _format_addr('%s <%s>' % (to_name, to_addr)) for to_addr, to_name in zip(config.addr, config.name) ]) msg['Subject'] = Header(subject, 'utf-8').encode() if message: msg.attach(MIMEText('%s' % message, 'plain', 'utf-8')) if files: for filepath in files: with open(filepath, 'rb') as f: part = MIMEBase('application', 'octet-stream') part.add_header( 'Content-Disposition', 'attacment', filename=os.path.basename(filepath)) part.set_payload(f.read()) encoders.encode_base64(part) msg.attach(part) while True: try: server = smtplib.SMTP(smtp_server, smtp_port) server.starttls() server.login(user, password) server.sendmail(from_addr, config.addr, msg.as_string()) server.quit() now = str(datetime.datetime.now().replace(second=0, microsecond=0)) for to_addr in config.addr: print('%s: Send email to %s successfully!\n' % (now, to_addr)) except: raise time.sleep(300) else: break
def test_does_not_multipart(self): from email.mime.multipart import MIMEMultipart from email.mime.multipart import MIMEBase msg = MIMEMultipart() body = MIMEBase('x-application', 'not-text') body.set_payload('I am full of happy babies. All Days for Me!') msg.attach(body) other = MIMEBase('application', 'pdf') other.set_payload('Not really a pdf.') msg.attach(other) fut = self._make_one() self.assertEqual(fut(msg), None)
def add_figure(self, plt, imgid=1): buf = io.BytesIO() plt.savefig(buf, format = 'png') buf.seek(0) msgText = '<br><img src="cid:image{0}"><br>'.format(imgid) self.body = self.body + msgText part = MIMEBase('application', "octet-stream") part.set_payload( buf.read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % 'figure.png') part.add_header('Content-ID', '<image{0}>'.format(imgid)) self.msg.attach(part) buf.close() #close buffer
def send_mail_with_file(content, args): r_content = '<html><body>' + u'<h1>嘿嘿哈哈</h1>' # message obj msg = MIMEMultipart() msg['From'] = _format_addr(u'小王 <%s>' % sender) msg['To'] = _format_addr(u'嘿嘿嘿 <%s>' % ','.join(receivers)) msg['Subject'] = Header(u'老王准备嘿嘿嘿了', 'utf-8').encode() # add add_ons for idx, img in enumerate(args): try: with open('img/%s' % img, 'rb') as f: filename=str(idx)+'.jpg' # set MIME and filename # there is a keng mime = MIMEBase('image', 'jpg', filename=filename) # add header info mime.add_header('Content-Disposition', 'attachment', filename=filename) mime.add_header('Content-ID', '<%s>' % idx) mime.add_header('X-Attachment-ID', str(idx)) # add file content mime.set_payload(f.read()) # base64 encode encoders.encode_base64(mime) # attach with msg msg.attach(mime) r_content += '<p><img src="cid:%s"></p>' % idx except: # raise continue # replace \n with <br /> in content # pattern = re.compile('\n') # content = re.sub(r'\n', '<br />\n ', content) r_content = prefix + content + prefix + '</body></html>' # content text msg.attach(MIMEText(r_content, 'html', 'utf-8')) # send server = smtplib.SMTP(smtp_server, 25) # server.set_debuglevel(1) server.login(sender, sender_password) server.sendmail(sender, receivers, msg.as_string()) server.quit()
def prepare_attachment(self, path): filename = os.path.split(path)[1] bookname = filename.split('.')[0] booktype = filename.split('.')[1] with open(path, 'rb') as f: # 设置附件的MIME和文件名,这里是png类型: mime = MIMEBase(bookname, booktype, filename=filename) # 加上必要的头信息: mime.add_header('Content-Disposition', 'attachment', filename=filename) mime.add_header('Content-ID', '<0>') mime.add_header('X-Attachment-Id', '0') # 把附件的内容读进来: mime.set_payload(f.read()) # 用Base64编码: encoders.encode_base64(mime) # 添加到MIMEMultipart: return mime
def test_does_not_match_multipart_w_no_charset_not_utf8(self): """ Simulates mime messages created by stdlib email parser where a part can have a charset set in the Content-Type header but get_charset() returns None. """ from email.mime.multipart import MIMEMultipart from email.mime.multipart import MIMEBase from email.mime.text import MIMEText body_text = u'Non \xe8 giusto costringermi ad usare il modulo email.' msg = MIMEMultipart() body = MIMEText(body_text.encode('ISO-8859-1')) body.set_charset(None) msg.attach(body) other = MIMEBase('application', 'pdf') other.set_payload('Not really a pdf.') msg.attach(other) fut = self._make_one() self.assertEqual(fut(msg), None)
def test_matches_multipart_w_bogus_charset_in_content_type(self): """ Simulates mime messages created by stdlib email parser where a part can have a charset set in the Content-Type header but get_charset() returns None. """ from email.mime.multipart import MIMEMultipart from email.mime.multipart import MIMEBase from email.mime.text import MIMEText msg = MIMEMultipart() body = MIMEText('I am full of happy babies. All days for Me!') body.set_charset(None) del body['Content-Type'] body['Content-Type'] = 'text/plain; charset=bogus; flow=groovy' msg.attach(body) other = MIMEBase('application', 'pdf') other.set_payload('Not really a pdf.') msg.attach(other) fut = self._make_one() self.assertEqual(fut(msg), "body_regexp: body matches u'happy.+days'")
def send(self, to, subject, message, attachments=None): """ Send an email. May also include attachments. to -- The email recipient. subject -- The email subject. message -- The email body. attachments -- A list of file names to include. """ if attachments is None: attachments = [] msg = MIMEMultipart() msg.attach(MIMEText(message)) for path in attachments: content_type, encoding = mimetypes.guess_type(path) if content_type is None or encoding is not None: content_type = 'application/octet-stream' main_type, subtype = content_type.split('/', 1) with open(path, 'rb') as file: data = file.read() attachment = MIMEBase(main_type, subtype) attachment.set_payload(data) email.encoders.encode_base64(attachment) attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(path)) msg.attach(attachment) msg['To'] = to msg['From'] = self.__username msg['Subject'] = subject log.debug('GMAIL: Sending email to %s' % msg['To']) errors = self.smtp.sendmail(self.__username, to, msg.as_string()) return msg, errors
def create_message(path): "Return a Message object with the file at path attached" d, fname = os.path.split(path) # create the outer message msg = MIMEMultipart() msg['From'] = email.utils.formataddr((OPTIONS['name'], OPTIONS['email'])) fname_parts = fname.split('::') if len(fname_parts) == 2: to_addr, att_name = fname_parts[0], fname_parts[1] else: raise FeedbackError("Bad filename: %s; can't determine recipient or attachment name" % fname) msg['To'] = to_addr msg['Subject'] = OPTIONS['feedback_subject'] # first part: the text/plain message derived from FEEDBACK_MSG body = MIMEText(FEEDBACK_MSG % {'signature' : OPTIONS['name']}) msg.attach(body) # second part: attachment ctype, encoding = mimetypes.guess_type(path) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) f = open(path, 'rb') att = MIMEBase(maintype, subtype) att.set_payload(f.read()) email.encoders.encode_base64(att) att.add_header('Content-Disposition', 'attachment', filename=att_name) msg.attach(att) logging.info("Created feedback message for %s from file %s" % (to_addr, path)) return msg
def test_matches_multipart(self): from email.mime.multipart import MIMEMultipart from email.mime.multipart import MIMEBase from email.mime.text import MIMEText msg = MIMEMultipart() body = MIMEText('I am full of happy babies. All days for Me!') msg.attach(body) other = MIMEBase('application', 'pdf') other.set_payload('Not really a pdf.') msg.attach(other) fut = self._make_one() self.assertEqual(fut(msg), "body_regexp: body matches u'happy.+days'") msg = MIMEMultipart() body = MIMEText("I can't remember if my amnesia is getting worse.") msg.attach(body) other = MIMEBase('application', 'pdf') other.set_payload('Not really a pdf.') msg.attach(other) self.assertEqual(fut(msg), "body_regexp: body matches u'amnesia'")
def test_matches_multipart_w_comment_in_charset(self): """ At least one email client out there generates content type headers that look like:: Content-Type: text/html; charset="utf-8" //iso-8859-2 """ from email.mime.multipart import MIMEMultipart from email.mime.multipart import MIMEBase from email.mime.text import MIMEText msg = MIMEMultipart() body = MIMEText('I am full of happy babies. All days for Me!') body.set_charset(None) del body['Content-Type'] body['Content-Type'] = 'text/plain; charset="utf-8" //iso-8859-2' msg.attach(body) other = MIMEBase('application', 'pdf') other.set_payload('Not really a pdf.') msg.attach(other) fut = self._make_one() self.assertEqual(fut(msg), "body_regexp: body matches u'happy.+days'")
def create_multipart_message(atom_file, binary_file, dat_file): # first build the full MIME message using the email library msg = MIMEMultipart("related") entry = open(atom_file, "rb") atom = MIMEBase("application", "atom+xml") atom['Content-Disposition'] = 'attachment; name="atom"' atom.set_payload(entry.read()) msg.attach(atom) zip = open(binary_file, 'rb') base = MIMEBase("application", "zip") base['Content-Disposition'] = 'attachment; name="payload"; filename="example.zip"' base.set_payload(zip.read()) encoders.encode_base64(base) msg.attach(base) # now, to make it work with HTTP pull out the main headers headers = {} header_mode = True body = [] for line in msg.as_string().splitlines(True): if line == "\n" and header_mode: header_mode = False if header_mode: (key, value) = line.split(":", 1) headers[key.strip()] = value.strip() else: body.append(line) body = "".join(body) # write the body to the dat file o = open(dat_file, "wb") o.write(body) return headers
def attachments(self): folder = self._attachments_folder if folder is None: return [], [], {} profile = self.profile request = self.request attachments = [] attachment_links = [] attachment_hrefs = {} for name, model in folder.items(): if profile.alert_attachments == 'link': attachment_links.append(name) attachment_hrefs[name] = resource_url(model, request) elif profile.alert_attachments == 'attach': with model.blobfile.open() as f: f.seek(0, 2) size = f.tell() if size > MAX_ATTACHMENT_SIZE: attachment_links.append(name) attachment_hrefs[name] = resource_url(model, request) else: f.seek(0, 0) data = f.read() type, subtype = model.mimetype.split('/', 1) attachment = MIMEBase(type, subtype) attachment.set_payload(data) Encoders.encode_base64(attachment) attachment.add_header( 'Content-Disposition', 'attachment; filename="%s"' % model.filename) attachments.append(attachment) return attachments, attachment_links, attachment_hrefs
def send(self): # 邮件对象: msg = MIMEMultipart() msg['From'] = _format_addr('Python爱好者 <%s>' % from_addr) msg['To'] = _format_addr('管理员 <%s>' % to_addr) msg['Subject'] = Header('来自SMTP的问候……', 'utf-8').encode() # 邮件正文是MIMEText: msg.attach(MIMEText('send with file...', 'plain', 'utf-8')) # 添加附件就是加上一个MIMEBase,从本地读取一个图片: with open('/Users/michael/Downloads/test.png', 'rb') as f: # 设置附件的MIME和文件名,这里是png类型: mime = MIMEBase('image', 'png', filename='test.png') # 加上必要的头信息: mime.add_header('Content-Disposition', 'attachment', filename='test.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)
def enviar_correo(self, correo_dest, asunto, cuerpo, intento=0, *rutas_adjuntos): """ Se envía un correo bajo el nombre indicado a mailer y sobre la conexión establecida en este, con los elementos cómunes de un correo, que se le pasan como argumentos. :param correo_dest: :param asunto: :param cuerpo: :param intento: para indicar el número de reintento. :param rutas_adjuntos: :return: """ if True in (type(x) is not str for x in (correo_dest, asunto, cuerpo)): raise Exception(__name__ + '.sendMail params must be str') if self.smtp_host == 'smtp.sendgrid.net': origen = '*****@*****.**' else: origen = self.email_origen enviado = False # Podríamos verificar cnx sigue, aunque sino ya saltara excepción. try: # Preparamos las cabeceras de addrs fromadrr = Address(self.nombre_origen, addr_spec=origen) name, addr = parseaddr(correo_dest) toaddr = Address(name, addr_spec=addr) # Encapsulamos el mensaje msg = MIMEMultipart() # Para poder combinar fragmentos de <> MIME msg['From'] = formataddr((fromadrr.display_name, fromadrr.addr_spec)) msg['To'] = formataddr((toaddr.display_name, toaddr.addr_spec)) msg['Subject'] = asunto msg['Date'] = format_datetime(localtime()) # Construir msg (MIME de texto) y añadir al contenedor msg.attach(MIMEText(cuerpo, 'plain')) # Adición de los adjuntos, a msg. for ruta in rutas_adjuntos: rutap = os.path.abspath(ruta) if not os.path.exists(rutap): # notificarlo de alguna forma print('{} error:\t fallo adjuntando {} para {}'.format( __name__, rutap, origen)) continue #with open(rutap) as fp: # part = MIMEText(fp.read(), _subtype='plain') part = MIMEBase('application', "octet-stream") part.set_payload(open(rutap, "rb").read()) encoders.encode_base64(part) # part.add_header('Content-Disposition', # 'attachment; filename="{}"'.format(os.path.basename(rutap))) part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(os.path.basename(rutap))) msg.attach(part) # server.sendmail(fromadrr.addr_spec, tomail, msg.as_string()) self.smtpserver.send_message(msg) enviado = True self._incr_numenviados() except SMTPException as smtpe: print('RECONECTADO y REENVIO POR EXCEPT') if intento < mailer.REINTENTOS and not enviado: self._conectar() self.enviar_correo(correo_dest, asunto, cuerpo, intento+1, *rutas_adjuntos) else: raise except: raise
def send(self, emails): if isinstance(emails, Email): emails = [emails] if len([e for e in emails if e.__class__ != Email]): raise TypeError('emails must be Email or list of Email instances') smtpclass = SMTP_SSL if self.ssl else SMTP if self.server == 'localhost': smtp = smtpclass(self.server) else: smtp = smtpclass(self.server, self.port) if self.tls: smtp.starttls() if self.login and self.password: smtp.login(self.login, self.password) for email in emails: c = Charset(email.charset) c.header_encoding = QP c.body_encoding = 0 r = Charset(email.charset) r.header_encoding = 0 r.body_encoding = 0 email.normalize_email_list('rcpt') email.normalize_email_list('cc') email.normalize_email_list('bcc') mime1, mime2 = email.mimetype.split('/') mainpart = MIMEBase(mime1, mime2) if not email.force_7bit: mainpart.set_param('charset', email.charset) if len(email.attachments): message = MIMEMultipart('mixed') message.attach(mainpart) del mainpart['mime-version'] else: message = mainpart message['Date'] = datetime.datetime.now().strftime( '%a, %d %b %Y %H:%M:%S') + (" +%04d" % (time.timezone/-36,)) h = Header(maxlinelen=1000) # FIXME: what is correct max length? fromname = self.fromname.encode(email.charset, 'xmlcharrefreplace') h.append(fromname, r if is7bit(fromname) else c) h.append('<%s>' % self.email, r) message['From'] = h message['To'] = email.get_emails_header('rcpt') if len(email.cc): message['CC'] = email.get_emails_header('cc') if len(email.bcc): message['BCC'] = email.get_emails_header('bcc') subject = email.subject.encode(email.charset, 'xmlcharrefreplace') message['Subject'] = Header(subject, r if is7bit(subject) else c) if email.reply_to: message['Reply-To'] = email.get_emails_header('reply_to') if email.force_7bit: body = email.body.encode('ascii', 'xmlcharrefreplace') else: body = email.body.encode(email.charset, 'xmlcharrefreplace') mainpart.set_payload(body) if is7bit(body): mainpart['Content-Transfer-Encoding'] = '7bit' else: encode_quopri(mainpart) for attachment in email.attachments: if attachment.__class__ != Attachment: raise TypeError("invalid attachment") mimetype = attachment.mimetype if not mimetype: mimetype, encoding = guess_type(attachment.filename) if not mimetype: mimetype = 'application/octet-stream' mime1, mime2 = mimetype.split('/') part = MIMEBase(mime1, mime2) # using newer rfc2231 (not supported by Outlook): # part.set_param('name', attachment.filename.encode('utf-8'), charset = 'utf-8') # hack: using deprecated rfc2047 - supported by Outlook: part.set_param('name', str(Header(attachment.filename))) del part['mime-version'] if attachment.id: part['Content-Disposition'] = 'inline' else: part['Content-Disposition'] = 'attachment' # using newer rfc2231 (not supported by Outlook): # part.set_param('filename', # attachment.filename.encode('utf-8'), # 'Content-Disposition', # charset = 'utf-8') # hack: using deprecated rfc2047 - supported by Outlook: part.set_param('filename', str(Header(attachment.filename)), 'Content-Disposition') if attachment.id: part['Content-ID'] = '<%s>' % attachment.id part.set_payload(attachment.content) encode_base64(part) # Do this AFTER encode_base64(part), or Content-Transfer-Encoding header will duplicate, # or even happen 2 times with different values. if attachment.charset: part.set_charset(attachment.charset) message.attach(part) smtp.sendmail(self.email, [rcpt[1] for rcpt in email.rcpt] + [cc[1] for cc in email.cc] + [bcc[1] for bcc in email.bcc], message.as_string()) smtp.quit()
htmlFile = open("html/genialnosti_table.html", "rU") htmlFile = htmlFile.read() part1 = MIMEText(htmlFile, 'html') #!!!! part1.set_charset('utf-8') msg.attach(part1) #----------------------------------------------------------------------------------------------------------------------- # add attach file1 part = MIMEBase('application', "octet-stream") filename = projectPath + "/docs/genialnost/Antonio_Gaudi.docx" part.set_payload(open(filename, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % 'Антонио Гауди.docx') msg.attach(part) #----------------------------------------------------------------------------------------------------------------------- # add attach file2 part = MIMEBase('application', "octet-stream") filename = projectPath + "/docs/genialnost/Arkhetipy_Sinergia_partnerstva.doc" part.set_payload(open(filename, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % 'Архетипы. Синергия партнерства.doc') msg.attach(part) #----------------------------------------------------------------------------------------------------------------------- # add attach file3 part = MIMEBase('application', "octet-stream")
def PostPhoto(Auth, PublisherUserID, AlbumName, PhotoPath, Title="Default Title", Summary="Set via Picasa API"): # POST https://picasaweb.google.com/data/feed/api/user/userID/albumid/albumID # https://picasaweb.google.com/data/feed/api/user/userID/albumid/albumID """ Should post the file to the selecter Album """ ListAlbumUrl = "/data/feed/api/user/" + PublisherUserID AlbumID = Album_IDfromAlbumName(AlbumName, Auth, ListAlbumUrl) PostUrl = "/data/feed/api/user/" + PublisherUserID + "/albumid/" + AlbumID # print "PostUrl:",PostUrl # Annotation Forming: # To define a spectial Function for that: TextToMime = "<entry xmlns='http://www.w3.org/2005/Atom'><title>" TextToMime = TextToMime + Title TextToMime = TextToMime + "</title><summary>" TextToMime = TextToMime + Summary TextToMime = ( TextToMime + "</summary><category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/photos/2007#photo'/></entry>" ) # Creating a connection Pic_Connection = httplib.HTTPSConnection(Picasa_Host) Pic_Connection.set_debuglevel(DEBUG_LEVEL) header = { "Authorization": "GoogleLogin auth=" + Auth, "Content-type": "multipart/related;boundary=END_OF_PART", "Accept": "*/*", "MIME-Version": "1.0", } # Creating Multipart Container Msg = MIMEMultipart("related", "END_OF_PART") # Creatinf XML part XmlToAdd = MIMEBase("application", "atom+xml") XmlToAdd.set_payload(TextToMime) Msg.attach(XmlToAdd) # Creating Image part FilePath = PhotoPath # FilePath='/Users/denirz/Pictures/Keni.jpg' basefile = MIMEBase("image", "jpeg") Fd = open(FilePath, "rb") basefile.set_payload(Fd.read()) Fd.close() Msg.attach(basefile) # now message is ready, so let's generate string to post: DataToSend = Msg.as_string() if DEBUG_LEVEL: print "see content in ./message.txt file" MsgFile = open("./message.txt", "w") MsgFile.write(DataToSend) MsgFile.close() # now sending rewuest Pic_Connection.request("POST", PostUrl, DataToSend, header) RetAnswer = Pic_Connection.getresponse() # print RetAnswer.getheaders() # xmlFilePut=open('./post.xml','wb') # xmlFilePut.write(RetAnswer.read()) # xmlFilePut.close() address = UploadedPictureAddres(RetAnswer.read()) return address
def message(self): if self._message is not None: return self._message community = self._community request = self.request profile = self.profile blogentry = self._blogentry community_href = model_url(community, request) blogentry_href = model_url(blogentry, request) manage_preferences_href = model_url(profile, request) system_name = get_setting(self.context, "system_name", "KARL") system_email_domain = get_setting(self.context, "system_email_domain") reply_to = "%s <%s+blog-%s@%s>" % (community.title.replace(',', ''), community.__name__, docid_to_hex(blogentry.docid), system_email_domain) attachments = [] attachment_links = [] attachment_hrefs = {} for name,model in self._attachments.items(): if profile.alert_attachments == 'link': attachment_links.append(name) attachment_hrefs[name] = model_url(model, request) elif profile.alert_attachments == 'attach': with model.blobfile.open() as f: f.seek(0, 2) size = f.tell() if size > MAX_ATTACHMENT_SIZE: attachment_links.append(name) attachment_hrefs[name] = model_url(model, request) else: f.seek(0, 0) data = f.read() type, subtype = model.mimetype.split('/', 1) attachment = MIMEBase(type, subtype) attachment.set_payload(data) Encoders.encode_base64(attachment) attachment.add_header( 'Content-Disposition', 'attachment; filename="%s"' % model.filename) attachments.append(attachment) body_template = get_template(self._template) from_name = "%s | %s" % (self.creator.title, system_name) msg = MIMEMultipart() if attachments else Message() msg["From"] = "%s <%s>" % (from_name, self.mfrom) msg["To"] = "%s <%s>" % (profile.title, profile.email) msg["Reply-to"] = reply_to msg["Subject"] = self._subject body_text = body_template( context=self.context, community=community, community_href=community_href, blogentry=blogentry, blogentry_href=blogentry_href, attachments=attachment_links, attachment_hrefs=attachment_hrefs, manage_preferences_href=manage_preferences_href, profile=profile, profiles=self.profiles, creator=self.creator, digest=self.digest, alert=self, history=self._history, ) if self.digest: # Only interested in body for digest html = document_fromstring(body_text) body_element = html.cssselect('body')[0] span = etree.Element("span", nsmap=body_element.nsmap) span[:] = body_element[:] # Copy all body elements to an empty span body_text = etree.tostring(span, pretty_print=True) if isinstance(body_text, unicode): body_text = body_text.encode('utf-8') if attachments: body = MIMEText(body_text, 'html', 'utf-8') msg.attach(body) for attachment in attachments: msg.attach(attachment) else: msg.set_payload(body_text, 'utf-8') msg.set_type("text/html") self._message = msg return self._message
from_addr = '*****@*****.**' password = '******' to_addr = '*****@*****.**' smtp_server = 'smtp.126.com' msg = MIMEMultipart() msg['From'] = _format_addr('PythonTest <%s>' % from_addr) msg['To'] = _format_addr('Admin <%s>' % to_addr) msg['Subject'] = Header('Hello from SMTP...', 'utf-8').encode() msg.attach(MIMEText('Send with file...', 'plain', 'utf-8')) with open('E:/pic/test.jpg', 'rb') as f: mime = MIMEBase('image', 'png', filename='test.jpg') mime.add_header('Content-Disposition', 'attachment', filename='test.hpg') mime.add_header('Content-ID', '<0>') mime.add_header('X-Attachment-ID', '<0>') mime.set_payload(f.read()) encoders.encode_base64(mime) msg.attach(mime) server = smtplib.SMTP(smtp_server, 25) server.set_debuglevel(1) server.login(from_addr, password) server.sendmail(from_addr, [to_addr], msg.as_string()) server.quit()