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 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 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 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(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(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 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 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 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 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 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_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 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)
# 如果Email中要加上附件怎么办?带附件的邮件可以看做包含若干部分的邮件:文本和各个附件本身,所以,可以构造一个MIMEMultipart对象代表邮件本身,然后往里面加上一个MIMEText作为邮件正文,再继续往里面加上表示附件的MIMEBase对象即可: # # 邮件对象: from email.mime.multipart import MIMEMultipart, MIMEBase 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('code.jpg', 'rb') as f: # # 设置附件的MIME和文件名,这里是png类型: mime = MIMEBase('image', 'jpeg', filename='code.jpg') # # 加上必要的头信息: mime.add_header('Content-Disposition', 'attachment', filename='code.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) # 然后,按正常发送流程把msg(注意类型已变为MIMEMultipart)发送出去,就可以收到如下带附件的邮件: # 发送图片 # 如果要把一个图片嵌入到邮件正文中怎么做?直接在HTML邮件中链接图片地址行不行?答案是,大部分邮件服务商都会自动屏蔽带有外链的图片,因为不知道这些链接是否指向恶意网站。 # 要把图片嵌入到邮件正文中,我们只需按照发送附件的方式,先把邮件作为附件添加进去,然后,在HTML中通过引用src="cid:0"就可以把附件作为图片嵌入了。如果有多个图片,给它们依次编号,然后引用不同的cid:x即可。 # 把上面代码加入MIMEMultipart的MIMEText从plain改为html,然后在适当的位置引用图片: # msg.attach(MIMEText('<html><body><h1>Hello</h1>' +
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()
def send_email(self): self.new_window() msg = MIMEMultipart() msg['Subject'] = "SF360 :: Task :: Dashboard Updates" msg['From'] = self.from_email msg['To'] = self.to_email msg_text = "Hi Support,\n\nCan you please complete the dashboard updates as per the attached files?\n\nThank you,\nFood News App \n\nThis task of Dashboard Updates has been assigned a SOC 2 risk of minor as per the document: https://go.safefood360.com/MasterData/DocumentControl/ViewDocument/4da849b1-db55-4558-9022-ab7200b32ccc" try: attachment_path_list = [self.csv_path, self.sql_path] status_text = "Email Sent" except: status_text = "Please save both\nCSV & SQL files" if status_text == "Email Sent": for each_file_path in attachment_path_list: #try: file_name = each_file_path.split("/")[-1] part = MIMEBase("application", "octet-stream") part.set_payload(open(each_file_path, "rb").read()) encoders.encode_base64(part) part.add_header("Content-Disposition", "attachment", filename=file_name) msg.attach(part) #except: #print("could not attache file") msg.attach(MIMEText(msg_text)) try: mailserver = smtplib.SMTP('smtp.office365.com', 587) mailserver.ehlo() mailserver.starttls() mailserver.login(self.from_email, self.from_pw) mailserver.sendmail(msg['From'], msg['To'], msg.as_string()) mailserver.quit() except: status_text == "Failed to send email" space_label = ttk.Label(self.win, text="") space_label.config(font=("Arial", 10)) space_label.pack() self.status_text = ttk.Label(self.win, text=status_text, anchor=N) self.status_text.config(font=("Arial", 12)) self.status_text.pack() space_label = ttk.Label(self.win, text="") space_label.config(font=("Arial", 15)) space_label.pack() self.close_button = ttk.Button(self.win, text="Ok", command=self.close_pop_up, width=12, style='my.TButton') self.close_button.pack()
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
def _send_email_generic(text, html_, subject, to_, from_, password=None, files=None, multipart_type='alternative'): """ Function to send email from a specific account. Use local mta agent if from_==TRADING_SYSTEM_EMAIL, otherwise needs login and password. A wrapper around this function such as send_trading_system_email is highly recommend to avoid having the password everywhere. :param text: (str) Text to include in the email content (added as <p>text</p> if html_ specified) :param html_: (str) Html to include in the email content (after text if specific) :param subject: (str) Subject of the email :param to_: (iterable of str) or (str) Recipients of the emails :param from_: email address of the account to use to send email :param password: password of the account to use to send email :param files: (list of str) or (str) files paths + names to attach to the email :return: result of the send """ if files is None: files = [] if isinstance(files, str): files = [files] if html_ is not None and text is not None: html_ = '<p>' + text + '</p>' + html_ text = None msg = MIMEMultipart(multipart_type) msg['Subject'] = subject msg['From'] = from_ msg['To'] = to_ if isinstance(to_, basestring) else '; '.join(to_) if text is not None: msg_text = MIMEText(text, 'plain') msg.attach(msg_text) if html_ is not None: msg_html = MIMEText(html_, 'html', _charset='utf-8') msg.attach(msg_html) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload(open(f, "rb").read()) Encoders.encode_base64(part) attachment_name = f.split('/')[-1] part.add_header('Content-Disposition', 'attachment; filename="' + attachment_name + '"') msg.attach(part) sent = False if TRADING_SYSTEM_EMAIL in from_: try: smtp = smtplib.SMTP('localhost') res_send = smtp.sendmail(from_, to_, msg.as_string()) sent = True except Exception: pass if not sent: smtp = smtplib.SMTP('smtp.gmail.com', 587) smtp.ehlo() smtp.starttls() smtp.login(from_, password) res_send = smtp.sendmail(from_, to_, msg.as_string()) smtp.quit() return res_send
msg['Subject'] = Header(u'来自我的问候...嘿嘿嘿', 'utf-8').encode() # 邮件正文是MIMEText: #msg = MIMEText('hello baby, guess who am I.——send by Python', 'plain', 'utf-8') msg_text = MIMEText( '<html><body><h1>Hello, Baby</h1>' + '<p>send by <a href="http://www.python.org">Python</a>...</p>' + '</body></html>', 'html', 'utf-8') msg.attach(msg_text) # 添加附件就是加上一个MIMEBase,从本地读取一个图片: with open('/home/cbc/DL/fast-neural-style-master/1_wave.png', 'rb') as f: # 设置附件的MIME和文件名,这里是png类型: mime = MIMEBase('image', 'png', filename='wangzi.png') # 加上必要的头信息: mime.add_header('Content-Disposition', 'attachment', filename='wangzi.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) with open('/home/cbc/图片/beauty/2.jpeg', 'rb') as f: # 设置附件的MIME和文件名,这里是png类型: mime = MIMEBase('image', 'jpeg', filename='gongzhu.jpeg') # 加上必要的头信息: mime.add_header('Content-Disposition', 'attachment', filename='gongzhu.jpeg')
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") filename = projectPath + "/docs/genialnost/kurs_po_raskrytiyu_potentsiala_2.doc"
def sendEmail(self, data_report, to_address): from_user = data_report.settings.get("EMAIL_USER") to_user = to_address msg = MIMEMultipart() msg['Subject'] = Header( data_report.settings.get("DATA_REPORT_TITLE", data_report.name), 'utf-8').encode() msg['To'] = from_user msg['From'] = to_user if data_report.settings.get("SVG_FILE"): read_svg_name = data_report.svg_file_name send_svg_name = "{0}".format(read_svg_name.split('/')[-1]) css = "<style>.showy {height: 100% !important;width: 100% !important;}\n.no-showy {display: none;}\n</style>" with open(read_svg_name, 'rb') as f: mime = MIMEBase('xml', 'svg', filename=send_svg_name) mime.add_header('Content-Disposition', 'attachment', filename=send_svg_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) msg.attach( MIMEText( css + '<img class="showy" width="0" height="0" src="cid:0">\n<img class="no-showy" src="my-image.jpg">', 'html', 'utf-8')) read_csv_name = data_report.csv_file_name send_csv_name = "{0}".format(read_csv_name.split('/')[-1]) with open(read_csv_name, 'rb') as f: mime = MIMEBase('xml', 'svg', filename=send_csv_name) mime.add_header('Content-Disposition', 'attachment', filename=send_csv_name) mime.add_header('Content-ID', '<1>') mime.add_header('X-Attachment-Id', '1') mime.set_payload(f.read()) encoders.encode_base64(mime) msg.attach(mime) self.smtp.sendmail(from_user, to_user, msg.as_string())
def formContent(msg): #添加文本 #发送纯文本内容 #msg=MIMEText('Hello,send by Python...','plain','utf-8') #发送html格式的正文 msg_text = MIMEText( '<html><body><h1>Hello</h1>' + '<p>send by <a href="http://www.python.org">Python</a>...</p>' + '<p><img src="cid:0"></p>' + '</body></html>', 'html', 'utf-8') msg.attach(msg_text) #添加附件 with open('C:\Users\...\Pictures\Devops.png', 'rb') as f: 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) with open('C:\Users\...\Pictures\Template.xlsx', 'rb') as f: mime = MIMEBase('file', 'xlsx', filename='test.xlsx') # 加上必要的头信息: mime.add_header('Content-Disposition', 'attachment', filename='test.xlsx') mime.add_header('Content-ID', '<1>') mime.add_header('X-Attachment-Id', '1') # 把附件的内容读进来: mime.set_payload(f.read()) # 用Base64编码: encoders.encode_base64(mime) # 添加到MIMEMultipart: msg.attach(mime)
password = input('Password:'******'To:') smtp_server = input('SMTP Server:') smtp_port = 587 msg = MIMEMultipart() msg['From'] = _format_addr('yao<%s>' % from_addr) msg['To'] = _format_addr('管理员<%s>' % to_addr) msg['Subject'] = Header('SMTP_test', 'utf-8').encode() msg.attach( MIMEText( '<html><body><h1>hello,my friend...</h1>' + '<p><img src="cid:0"></p>' + '</body></html>', 'html', 'utf-8')) with open('/Users/yaoming/Desktop/GitHub/thum.jpg', 'rb') as f: mime = MIMEBase('image', 'jpg', filename='thum.jpg') mime.add_header('Content-Disposition', 'attachment', filename='thum.jpg') mime.add_header('Content-ID', '<0>') mime.add_header('x-Attachment-id', 'ID') mime.set_payload(f.read()) encoders.encode_base64(mime) msg.attach(mime) server = smtplib.SMTP(smtp_server, smtp_port) server.starttls() server.set_debuglevel(1) server.login(from_addr, password) server.sendmail(from_addr, [to_addr], msg.as_string()) server.quit()
# 邮件正文是MIMEText: msg.attach(MIMEText('send with file...', 'html', 'utf-8')) #如果想直接在邮件中显示图片,以html形式发送,并<img src="cid:0">即可 #msg.attach(MIMEText('<html><body><h1>Hello</h1>' + # '<p><img src="cid:0"></p>' + # '</body></html>', 'html', 'utf-8')) # 添加附件就是加上一个MIMEBase,从本地读取一个图片: with open( r'C:\Users\yaoqi\PycharmProjects\untitled1\content\AceMig29摄影作品 朝霞.jpg', '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) server = smtplib.SMTP(smtp_server, 25) #server.starttls() 如果需要加密则使用starttls函数 server.set_debuglevel(1) server.login(from_addr, password) server.sendmail(from_addr, [to_addr], msg.as_string()) server.quit()
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_invite(self, call) -> None: """ Given a dict with appropriate values, emails ics calendar invite. """ CRLF = "\r\n" login = call['login'] FROM = call['from'] description = call['description'] + CRLF attendees = call['attendees'] organizer = call['organizer'] try: confirmation = os.environ['CAL_KEY'] except HaltException as ha: print("No authentication methods left to try.") #ddtstart = datetime.datetime.now() #dtoff = datetime.timedelta(days = 1) dur = datetime.timedelta(hours=1) #ddtstart = ddtstart +dtoff ddtstart = call['datetime'] ddtstart = ddtstart + datetime.timedelta(hours=5) dtend = ddtstart + dur dtstamp = datetime.datetime.now().strftime("%Y%m%dT%H%M%SZ") dtstart = ddtstart.strftime("%Y%m%dT%H%M%SZ") dtend = dtend.strftime("%Y%m%dT%H%M%SZ") description = description + CRLF attendee = "" for att in attendees: attendee += "ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ- PARTICIPANT;PARTSTAT=ACCEPTED;RSVP=TRUE" + CRLF + " ;CN=" + att + ";X-NUM-GUESTS=0:" + CRLF + " mailto:" + att + CRLF ical = "BEGIN:VCALENDAR" + CRLF + "PRODID:pyICSParser" + CRLF + "VERSION:2.0" + CRLF + "CALSCALE:GREGORIAN" + CRLF ical += "METHOD:REQUEST" + CRLF + "BEGIN:VEVENT" + CRLF + "DTSTART:" + dtstart + CRLF + "DTEND:" + dtend + CRLF + "DTSTAMP:" + dtstamp + CRLF + organizer + CRLF ical += "UID:FIXMEUID" + dtstamp + CRLF ical += attendee + "CREATED:" + dtstamp + CRLF + description + "LAST-MODIFIED:" + dtstamp + CRLF + "LOCATION:" + CRLF + "SEQUENCE:0" + CRLF + "STATUS:CONFIRMED" + CRLF ical += "SUMMARY:Call with Forest Mars: " + ddtstart.strftime( "%b %d %Y @ %H:%M" ) + CRLF + "TRANSP:OPAQUE" + CRLF + "END:VEVENT" + CRLF + "END:VCALENDAR" + CRLF body_tmpl = open('assets/email/body.txt', 'r') #email_body = call['body'] self.data = { "Name": call['who'], "Day": call['weekday'], "month_name": call['month_name'], "day": call['day'], "ord": call['ord'], "time_hour": call['hour'], "time_minutes": call['mins'], "ampm": call['ampm'] } # @FIXME email_body = body_tmpl.read().format(**self.data) body_bin = "This is the email body in binary - two steps" msg = MIMEMultipart('mixed') msg['From'] = FROM msg['Reply-To'] = FROM msg['To'] = ",".join(attendees) msg['Date'] = formatdate(localtime=True) msg['Subject'] = call['Subject'] part_email = MIMEText(email_body, "html") part_cal = MIMEText(ical, 'calendar;method=REQUEST') msgAlternative = MIMEMultipart('alternative') msg.attach(msgAlternative) ical_attach = MIMEBase('application/ics', ' ;name="%s"' % ("invite.ics")) ical_attach.set_payload(ical) encode_base64(ical_attach) ical_attach.add_header('Content-Disposition', 'attachment; filename="%s"' % ("invite.ics")) email_attach = MIMEText('', 'text/html') encode_base64(email_attach) email_attach.add_header('Content-Transfer-Encoding', "") msgAlternative.attach(part_email) msgAlternative.attach(part_cal) mailServer = smtplib.SMTP('smtp.gmail.com', 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(login, confirmation) mailServer.sendmail(FROM, attendees, msg.as_string()) mailServer.close()