def send_email(to, name, file): import smtplib, os from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders msg = MIMEMultipart() msg["Subject"] = "Your task is processed" msg["From"] = "poddy.org" msg["To"] = to msg.attach(MIMEText("Dear %s, thank you for using SourceAnalyzer Web!" % name)) msg.attach(MIMEText("See in attachment.")) part = MIMEBase("application", "octet-stream") f = open(file, "rb") part.set_payload(f.read()) f.close() Encoders.encode_base64(part) part.add_header("Content-Disposition", 'attachment; filename="%s"' % os.path.basename(file)) msg.attach(part) s = smtplib.SMTP("localhost") s.sendmail("*****@*****.**", [to], msg.as_string()) s.quit()
def send_mail(send_to, subject, text, file): msg = MIMEMultipart() msg['From'] = 'ITLand.Root <*****@*****.**>' msg['To'] = send_to msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text)) part = MIMEBase('application', "octet-stream") part.set_payload(open(file, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) msg.attach(part) #server = smtplib.SMTP('smtp.gmail.com:587') #server.starttls() #server.login('jenko.kov', 'efi42dekut') #server.sendmail(send_from, send_to, msg.as_string()) #server.quit() server = smtplib.SMTP('172.16.10.254:25') server.sendmail(send_from, send_to, msg.as_string()) server.quit()
def send_mail(_from_, to_, subject, text, files=None, server=config.MAIL_SERVER, port=config.MAIL_SERVER_PORT): assert isinstance(to_, (list, tuple)) if files is None: files = [] msg = MIMEMultipart() msg['From'] = _from_ msg['To'] = COMMASPACE.join(to_) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for file_name, file_content in files: part = MIMEBase('application', "octet-stream") part.set_payload( file_content ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % file_name) msg.attach(part) smtp = smtplib.SMTP(server, port=port) smtp.sendmail(_from_, to_, msg.as_string() ) smtp.close()
def send_mail(send_from, send_to, subject, text, files=[], html=None, server="localhost"): assert type(send_to)==list assert type(files)==list if html: msg = MIMEMultipart('alternative') textbody = dehtml(text) part1 = MIMEText(textbody, 'plain') part2 = MIMEText(text, 'html') msg.attach(part1) msg.attach(part2) else: msg = MIMEMultipart() msg.attach( MIMEText(text) ) msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject for f in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(f,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP(server) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def mail(to, subject, text, attach): msg = MIMEMultipart() print gmail_user msg['From'] = gmail_user realToString='' for s in to: realToString = realToString + s + "," # print realToString,to, [gmail_user]+[]+to msg['To'] = gmail_user#realToString msg['Subject'] = subject msg.attach(MIMEText(text)) #attach each file in the list for file in attach: part = MIMEBase('application', 'octet-stream') part.set_payload(open(file, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) 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, [gmail_user]+[]+to, msg.as_string()) # Should be mailServer.quit(), but that crashes... mailServer.close()
def mail(to, subject, text, attach): msg = MIMEMultipart() msg['From'] = gmail_user msg['To'] = to msg['Subject'] = subject msg.attach(MIMEText(text)) 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)) print os.path.basename 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()) # Should be mailServer.quit(), but that crashes... mailServer.close()
def sendEmail(to, subject, text, files=[]): assert type(to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = USERNAME msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for file in files: part = MIMEBase('application', "octet-stream") part.set_payload(open(file, "rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"'% os.path.basename(file)) msg.attach(part) server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo_or_helo_if_needed() server.starttls() server.ehlo_or_helo_if_needed() server.login(USERNAME,PASSWORD) server.sendmail(USERNAME, MAILTO, msg.as_string()) server.quit()
def send_email_csv_attach(toaddrs, mail, csv_fn, fromaddr=EMAIL_SENDER_ADDR): msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddrs msg['Subject'] = 'please check attached csv file for cr status' msg.preamble = 'You will not see this in a MIME-aware mail reader.\n' # To guarantee the message ends with a newline msg.epilogue = '' #body text = MIMEText(mail) msg.attach(text) #attachment csv = MIMEBase('text', 'x-comma-separated-values') fp = open(csv_fn, 'rb') csv.set_payload(fp.read()) Encoders.encode_base64(csv) csv.add_header('Content-Disposition', 'attachment', filename=os.path.basename(csv_fn)) msg.attach(csv) server = smtplib.SMTP('remotesmtp.mot.com') server.set_debuglevel(1) server.sendmail(fromaddr, toaddrs, msg.as_string()) server.quit()
def get_mail_text(self, fields, request, **kwargs): """ Get header and body of e-amil as text (string) This will create both parts of the e-mail: text and the XML file """ headerinfo, additional_headers, body = self.get_header_body_tuple(fields, request, **kwargs) body_xml = self.get_mail_text_in_xml(fields, request, **kwargs) self.safe_xml_in_filesystem(body_xml) mime_text = MIMEText(body, _subtype=self.body_type or 'html', _charset=self._site_encoding()) attachments = self.get_attachments(fields, request) outer = MIMEMultipart() outer.attach(mime_text) # write header for key, value in headerinfo.items(): outer[key] = value # write additional header for a in additional_headers: key, value = a.split(':', 1) outer.add_header(key, value.strip()) for attachment in attachments: filename = attachment[0] ctype = attachment[1] encoding = attachment[2] content = attachment[3] if ctype is None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': msg = MIMEText(content, _subtype=subtype) elif maintype == 'image': msg = MIMEImage(content, _subtype=subtype) elif maintype == 'audio': msg = MIMEAudio(content, _subtype=subtype) else: msg = MIMEBase(maintype, subtype) msg.set_payload(content) # Encode the payload using Base64 Encoders.encode_base64(msg) # Set the filename parameter msg.add_header('Content-Disposition', 'attachment', filename=filename) outer.attach(msg) ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) p = MIMEBase(maintype, subtype) p.set_payload(body_xml) p.add_header('content-disposition', 'attachment', filename='form.xml') Encoders.encode_base64(p) outer.attach(p) return outer.as_string()
def send_mail(send_from, send_to, subject, text, files=[], server="localhost"): assert type(send_to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(f,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) #Set Email smtp parameters smtp = smtplib.SMTP('smtp.gmail.com:587') smtp.starttls() smtp.login('*****@*****.**', 'pythonheat1') smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def mail(to, subject, text, attach=None, image=None): msg = MIMEMultipart() msg['From'] = GMAIL_USER msg['To'] = to msg['Subject'] = subject msg.attach(MIMEText(text)) if attach: part = MIMEBase('application', 'octet-stream') with open(attach, 'rb') as f: part.set_payload(f.read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attach)) msg.attach(part) if image: with open(image, 'rb') as f: part = MIMEImage(f.read(), name=os.path.basename(image)) 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 sendmail(self, destination, subject, message, attach = None): try: msg = MIMEMultipart() msg['From'] = self.username msg['Reply-to'] = self.username msg['To'] = destination msg['Subject'] = subject msg.attach(MIMEText(message)) if attach: 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 = SMTP("smtp.gmail.com", 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() try: mailServer.login(self.username, self.password) mailServer.sendmail(self.username, destination, msg.as_string()) finally: mailServer.close() except Exception, exc: sys.exit("Failed to send mail; %s" % str(exc))
def mail(to, frm, subject, text, attach, smtphost, smtpuser, smtppass): msg = MIMEMultipart() msg['From'] = frm msg['To'] = to msg['Subject'] = subject msg.attach(MIMEText(text)) if attach: 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(smtphost, 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(smtpuser, smtppass) mailServer.sendmail(smtpuser, to, msg.as_string()) # todo, we should keep server open if we send a list of emails, do this on a to user bases for lists # Should be mailServer.quit(), but that crashes... mailServer.close()
def sendMail(message, encoding='utf-8'): msg = MIMEMultipart('alternative') msg['Subject'] = Header(MAIL_TITLE.encode(encoding), encoding) msg['From'] = SENDER msg['To'] = SENDER text = message msg.attach(MIMEText(text.encode(encoding), 'html', encoding)) # Attach file if specified if FILE_JOINED: part = MIMEBase('application', 'octet-stream') part.set_payload(open(FILE_JOINED, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % FILE_JOINED.split("/")[-1]) msg.attach(part) s = smtplib.SMTP(HOST, PORT) s.starttls() s.login(SENDER, SENDER_PASSWORD) try: s.sendmail(SENDER, SENDER, msg.as_string()) except: s.quit() return '%s Failed to send mail' % (SENDER) s.quit() return '%s / mail sent !' % (SENDER)
def mail(to, subject, text, attach=None): msg = MIMEMultipart() msg['From'] = email_settings.email_from_addr msg['To'] = to msg['Subject'] = subject msg.attach(MIMEText(text)) if attach: print attach print os.path.normpath(attach) fp = open(attach, 'r') msg.attach(MIMEText(fp.read()))# Put the attachment in line also fp.close() 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(email_settings.email_from_addr, email_settings.gmail_pwd) mailServer.sendmail(email_settings.email_from_addr, to, msg.as_string()) # Should be mailServer.quit(), but that crashes... mailServer.close()
def send_mail(send_to, subject, text, files=[], server='localhost', username=None, password=None): send_from = '*****@*****.**' msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text)) for f in files: part = MIMEBase('application', 'octet-stream') part.set_payload(open(f, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % basename(f)) msg.attach(part) smtp = SMTP(server) if username is not None: smtp.login(str(username), str(password)) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def mail(to, cc, subject, text, attach): '''Sends email from [email protected]''' username = "******" password = "******" msg = MIMEMultipart() msg['From'] = username msg['To'] = ", ".join(to) msg['Subject'] = subject msg['Cc'] = ", ".join(cc) msg.attach(MIMEText(text)) 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.fordfound.org", 25) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(username, password) mailServer.sendmail(username, to+cc, msg.as_string()) mailServer.close()
def sendEmail(send_from, send_to, subject, text, cc_to=[], files=[], server="192.168.42.13"): assert type(send_to)==list assert type(files)==list msg=MIMEMultipart() msg.set_charset("utf-8") msg['From']=send_from msg['To']=COMMASPACE.join(send_to) if cc_to: assert type(cc_to)==list msg['cc']=COMMASPACE.join(cc_to) send_to.extend(cc_to) msg['Date']=formatdate(localtime=True) msg['Subject']=subject msg.attach(MIMEText(text)) for f in files: part=MIMEBase('application', "octet-stream") part.set_payload(open(f, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"'%Header(os.path.basename(f), 'utf-8')) msg.attach(part) smtp=smtplib.SMTP(server) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def send_mail(send_from, send_to, subject, text, files=[], server="localhost"): import smtplib import os from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders assert type(send_to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(f,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP(server) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def load_attachment(file): part = MIMEBase("application", "octet-stream") part.set_payload(open(file, "rb").read()) Encoders.encode_base64(part) part.add_header("Content-Disposition", 'attachment; filename="%s"' % os.path.basename(file)) return part
def SendEmail(fPaths, isAttachmt, body, toList, ccList, bccList, subject): HOST = "cormailgw.raleighnc.gov" #FROM = "*****@*****.**" FROM = "*****@*****.**" TO = toList CC = ccList BCC = bccList msg = MIMEMultipart() msg['FROM'] = FROM msg['TO'] = TO msg['CC'] = CC msg['BCC'] = BCC msg['Date'] = formatdate(localtime = True) msg['Subject'] = subject msg.attach(MIMEText(body)) if isAttachmt: for fPath in fPaths: part = MIMEBase('text/plain', 'octet-stream') part.set_payload(open(fPath, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(fPath)) msg.attach(part) print ("message attached") server = smtplib.SMTP(HOST) print ("Connected to server") server.sendmail(FROM, TO.split(",") + CC.split(",") + BCC.split(","), msg.as_string()) print ("Sending Email...") server.close() for fPath in fPaths: os.remove(fPath) print ("Email sent")
def sendEmailAlert(self): msg = MIMEMultipart() alert = "Found hit for {matches} in pastie {url}".format(matches=self.matchesToText(), url=self.url) # headers msg['Subject'] = yamlconfig['email']['subject'].format(subject=alert) msg['From'] = yamlconfig['email']['from'] msg['To'] = yamlconfig['email']['to'] # message body message = ''' I found a hit for a regular expression on one of the pastebin sites. The site where the paste came from : {site} The original paste was located here: {url} And the regular expressions that matched: {matches} The paste has also been attached to this email. # LATER below follows a small exerpt from the paste to give you direct context '''.format(site=self.site.name, url=self.url, matches=self.matchesToRegex()) msg.attach(MIMEText(message)) # original paste as attachment part = MIMEBase('application', "octet-stream") part.set_payload(self.pastie_content) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s.txt"' % (self.id)) msg.attach(part) # send out the mail try: s = smtplib.SMTP(yamlconfig['email']['server'], yamlconfig['email']['port']) if 'username' in yamlconfig['email'] and yamlconfig['email']['username']: s.login(yamlconfig['email']['username'], yamlconfig['email']['password']) s.sendmail(yamlconfig['email']['from'], yamlconfig['email']['to'], msg.as_string()) s.close() except smtplib.SMTPException, e: logger.error("ERROR: unable to send email: {0}".format(e))
def attach(self, filename, mime=None, charset=None, content=None): """Attach files to this message. Example:: msg.attach("me.png", mime="image/png") It also supports fake attachments:: msg.attach("fake.txt", mime="text/plain", content="gotcha") """ base = os.path.basename(filename) if content is None: fd = open(filename) content = fd.read() fd.close() elif not isinstance(content, types.StringType): raise TypeError("Don't know how to attach content: %s" % repr(content)) part = MIMEBase("application", "octet-stream") part.set_payload(content) Encoders.encode_base64(part) part.add_header("Content-Disposition", "attachment", filename=base) if mime is not None: part.set_type(mime) if charset is not None: part.set_charset(charset) if self.msg is None: self.msg = MIMEMultipart() self.msg.attach(self.message) self.msg.attach(part)
def attach(self, filename, mime=None, charset=None, content=None): base = os.path.basename(filename) if content is None: fd = open(filename) content = fd.read() fd.close() if not isinstance(content, types.StringType): raise TypeError("don't know how to handle content: %s" % type(content)) part = MIMEBase("application", "octet-stream") part.set_payload(content) Encoders.encode_base64(part) part.add_header("Content-Disposition", "attachment; filename=\"%s\"" % base) if mime is not None: part.set_type(mime) if charset is not None: part.set_charset(charset) if self.msg is None: self.msg = MIMEMultipart() self.msg.attach(self.message) self.msg.attach(part)
def send_report( self, subject, body, attachment, apptype='x/zip'): """ Send the email report to its destination. @type to: string @param to: Destination email address for the report. @type subject: string @param subject: The subject of the email message. @type body: string @param body: The body of the email message (includes report summary). @type attachment: string @param attachment: Path to report file for attaching to message. @type apptype: string @param apptype: Application MIME type for attachment. """ message = MIMEMultipart() message['From'] = self.emailfrom message['To'] = self.emailto message['Subject'] = subject message.attach( MIMEText( body )) part = MIMEBase('application',apptype) part.set_payload( open( attachment, 'r').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(attachment)) message.attach(part) conn = smtplib.SMTP(self.smtpserver, self.smtpport) conn.sendmail( message['From'], self.emailto, message.as_string()) conn.close()
def sendmail(subject): MAIL_FROM = '*****@*****.**' MAIL_TO = ['*****@*****.**'] BAK_DIR = '/path/to/bak/folder' msg = MIMEMultipart() msg['From'] = MAIL_FROM msg['Subject'] = subject msg.attach( MIMEText('test send attachment') ) for filename in os.listdir(BAK_DIR): part = MIMEBase('application', "octet-stream") part.set_payload(open(os.path.join(BAK_DIR, filename),"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(filename)) msg.attach(part) try: smtp = ExtendedSMTP() smtp.callback = callback smtp.connect('smtp.qq.com', 25) smtp.login('mymail', 'mypwd') smtp.sendmail(MAIL_FROM, MAIL_TO, msg.as_string()) smtp.close() os.system('rm -f %s/*' % BAK_DIR) except Exception, e: print e
def send_mail(send_from, send_to, subject, text, files=[], server="localhost",password=None,user=None): if type(send_to) in types.StringTypes: send_to = [send_to] if files is None: files = [] assert type(files)==list msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for f in files: part = MIMEBase('application', "octet-stream") content = open(f, 'rb').read() part.set_payload(content) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP(server) if password: if not user: user = msg['From'] smtp.starttls() smtp.login(user,password) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def send_mail(send_from, send_to, subject, text, files=[], server='smtp.typa.ru'): from smtplib import SMTP from os import path from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders from email.header import Header assert type(send_to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = Header(send_from.decode("utf-8")).encode() msg['To'] = Header(COMMASPACE.join(send_to).decode("utf-8")).encode() msg['Date'] = formatdate(localtime=True) msg['Subject'] = Header(subject.decode("utf-8")).encode() msg.attach( MIMEText(text,'plain','UTF-8') ) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(f,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % path.basename(f)) msg.attach(part) smtp = SMTP(server, 25) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def append(self, content=None, content_file_path=None, content_encondig=None, filename=None, content_type=None, **kwargs): if content_file_path: if content_type == None: (content_type, content_encondig) = mimetypes.guess_type(content_file_path, strict=False) if content == None: with open(content_file_path, 'r') as fh: content = fh.read() content_class = content.__class__.__name__ if content_class in self.mapper: message = self.mapper[content_class](self, content, **kwargs) else: if not content_type: content_type = guess_mime_type(content, 'binary/octet-stream') (maintype, subtype) = content_type.split('/') if maintype == 'text': message = MIMEText(content, _subtype=subtype) else: message = MIMEBase(maintype, subtype) message.set_payload(content) #Dont base64 encode rfc822 message, they will not be parsed if not content_type == 'message/rfc822': Encoders.encode_base64(message) if content_encondig != None: message['Content-Encoding'] = content_encondig if filename != None: message.add_header('Content-Disposition', 'attachment', filename=filename) if message != None: self.message.attach(message) else: raise OSLibError("Empty part added to user_data")
def send_mail(server, port, account, password, tls, _from, to, subject, message, files): conn = smtplib.SMTP(server, port, timeout=settings.SMTP_TIMEOUT) if tls: conn.starttls() if account and password: conn.login(account, password) email = MIMEMultipart() email['Subject'] = subject email['From'] = _from email['To'] = ', '.join(to) email.attach(MIMEText(message)) for file in reversed(files): part = MIMEBase('image', 'jpeg') with open(file, 'rb') as f: part.set_payload(f.read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) email.attach(part) if files: logging.debug('attached %d pictures' % len(files)) logging.debug('sending email message') conn.sendmail(_from, to, email.as_string()) conn.quit()
def OnSend(self, event): ''' Send the email using the filled out textboxes. Warn the user if they forget to fill part of it out. ''' From = self.fromTxt.GetValue() To = self.toTxt.GetValue() Subject = self.subjectTxt.GetValue() text = self.messageTxt.GetValue() colon = To.find(';') period = To.find(',') if colon != -1: temp = To.split(';') To = self.sendStrip(temp) #';'.join(temp) elif period != -1: temp = To.split(',') To = self.sendStrip(temp) #';'.join(temp) else: pass if To == '': print('add an address to the "To" field!') dlg = wx.MessageDialog( None, _('Please add an address to the "To" field and try again'), _('Error'), wx.OK | wx.ICON_EXCLAMATION) dlg.ShowModal() dlg.Destroy() elif Subject == '': dlg = wx.MessageDialog(None, _('Please add a "Subject" and try again'), _('Error'), wx.OK | wx.ICON_EXCLAMATION) dlg.ShowModal() dlg.Destroy() elif From == '': lg = wx.MessageDialog( None, _('Please add an address to the "From" field and try again'), _('Error'), wx.OK | wx.ICON_EXCLAMATION) dlg.ShowModal() dlg.Destroy() else: msg = MIMEMultipart() msg['From'] = From msg['To'] = To msg['Subject'] = Subject msg['Date'] = formatdate(localtime=True) msg.attach(MIMEText(text)) if self.filepaths != []: print('attaching file(s)...') for path in self.filepaths: part = MIMEBase('application', "octet-stream") part.set_payload(open(path, "rb").read()) Encoders.encode_base64(part) part.add_header( 'Content-Disposition', 'attachment; filename="%s"' % os.path.basename(path)) msg.attach(part) # edit this to match your mail server (i.e. mail.myserver.com) server = smtplib.SMTP('smtp.gmail.com:587') # open login dialog dlg = LoginDlg(server) res = dlg.ShowModal() if dlg.loggedIn: dlg.Destroy() # destroy the dialog try: failed = server.sendmail(From, To, msg.as_string()) server.quit() self.Close() # close the program except Exception as e: print('Error - send failed!') print(e) else: if failed: print('Failed:', failed) else: dlg.Destroy()
def build_email(self, email_from, email_to, subject, body, email_cc=None, email_bcc=None, reply_to=False, attachments=None, message_id=None, references=None, object_id=False, subtype='plain', headers=None, body_alternative=None, subtype_alternative='plain'): """Constructs an RFC2822 email.message.Message object based on the keyword arguments passed, and returns it. :param string email_from: sender email address :param list email_to: list of recipient addresses (to be joined with commas) :param string subject: email subject (no pre-encoding/quoting necessary) :param string body: email body, of the type ``subtype`` (by default, plaintext). If html subtype is used, the message will be automatically converted to plaintext and wrapped in multipart/alternative, unless an explicit ``body_alternative`` version is passed. :param string body_alternative: optional alternative body, of the type specified in ``subtype_alternative`` :param string reply_to: optional value of Reply-To header :param string object_id: optional tracking identifier, to be included in the message-id for recognizing replies. Suggested format for object-id is "res_id-model", e.g. "12345-crm.lead". :param string subtype: optional mime subtype for the text body (usually 'plain' or 'html'), must match the format of the ``body`` parameter. Default is 'plain', making the content part of the mail "text/plain". :param string subtype_alternative: optional mime subtype of ``body_alternative`` (usually 'plain' or 'html'). Default is 'plain'. :param list attachments: list of (filename, filecontents) pairs, where filecontents is a string containing the bytes of the attachment :param list email_cc: optional list of string values for CC header (to be joined with commas) :param list email_bcc: optional list of string values for BCC header (to be joined with commas) :param dict headers: optional map of headers to set on the outgoing mail (may override the other headers, including Subject, Reply-To, Message-Id, etc.) :rtype: email.message.Message (usually MIMEMultipart) :return: the new RFC2822 email message """ email_from = email_from or tools.config.get('email_from') assert email_from, "You must either provide a sender address explicitly or configure "\ "a global sender address in the server configuration or with the "\ "--email-from startup parameter." # Note: we must force all strings to to 8-bit utf-8 when crafting message, # or use encode_header() for headers, which does it automatically. headers = headers or {} # need valid dict later if not email_cc: email_cc = [] if not email_bcc: email_bcc = [] if not body: body = u'' email_body_utf8 = ustr(body).encode('utf-8') email_text_part = MIMEText(email_body_utf8, _subtype=subtype, _charset='utf-8') msg = MIMEMultipart() if not message_id: if object_id: message_id = tools.generate_tracking_message_id(object_id) else: message_id = make_msgid() msg['Message-Id'] = encode_header(message_id) if references: msg['references'] = encode_header(references) msg['Subject'] = encode_header(subject) msg['From'] = encode_rfc2822_address_header(email_from) del msg['Reply-To'] if reply_to: msg['Reply-To'] = encode_rfc2822_address_header(reply_to) else: msg['Reply-To'] = msg['From'] msg['To'] = encode_rfc2822_address_header(COMMASPACE.join(email_to)) if email_cc: msg['Cc'] = encode_rfc2822_address_header(COMMASPACE.join(email_cc)) if email_bcc: msg['Bcc'] = encode_rfc2822_address_header(COMMASPACE.join(email_bcc)) msg['Date'] = formatdate() # Custom headers may override normal headers or provide additional ones for key, value in headers.iteritems(): msg[ustr(key).encode('utf-8')] = encode_header(value) if subtype == 'html' and not body_alternative and html2text: # Always provide alternative text body ourselves if possible. text_utf8 = tools.html2text(email_body_utf8.decode('utf-8')).encode('utf-8') alternative_part = MIMEMultipart(_subtype="alternative") alternative_part.attach(MIMEText(text_utf8, _charset='utf-8', _subtype='plain')) alternative_part.attach(email_text_part) msg.attach(alternative_part) elif body_alternative: # Include both alternatives, as specified, within a multipart/alternative part alternative_part = MIMEMultipart(_subtype="alternative") body_alternative_utf8 = ustr(body_alternative).encode('utf-8') alternative_body_part = MIMEText(body_alternative_utf8, _subtype=subtype_alternative, _charset='utf-8') alternative_part.attach(alternative_body_part) alternative_part.attach(email_text_part) msg.attach(alternative_part) else: msg.attach(email_text_part) if attachments: for (fname, fcontent) in attachments: filename_rfc2047 = encode_header_param(fname) part = MIMEBase('application', "octet-stream") # The default RFC2231 encoding of Message.add_header() works in Thunderbird but not GMail # so we fix it by using RFC2047 encoding for the filename instead. part.set_param('name', filename_rfc2047) part.add_header('Content-Disposition', 'attachment', filename=filename_rfc2047) part.set_payload(fcontent) Encoders.encode_base64(part) msg.attach(part) return msg
from email import Encoders from email.mime.text import MIMEText emaillist = ['*****@*****.**'] msg = MIMEMultipart('mixed') msg['Subject'] = 'Arrest Warrent' msg['From'] = '*****@*****.**' msg['To'] = ', '.join(emaillist) part = MIMEBase('application', "octet-stream") part.set_payload( open( 'C:' + os.sep + 'Users' + os.sep + 'abangerx' + os.sep + 'Desktop' + os.sep + 'WarrentDetails.txt', "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="WarrentDetails.txt"') msg.attach(part) msg.add_header('To', msg['From']) text = "Dear Sir, \n\n An arrest warrent has been generated due to XYZ reason by ZZZ complain.\n YOU MUST APPEAR IN PERSON TO RESOLVE THIS MATTER. \n\n Regards,\n FBI :)" part1 = MIMEText(text, 'plain') msg.attach(part1) server = smtplib.SMTP_SSL("smtp.gmail.com", 465) # server.ehlo() # server.starttls() server.login("*****@*****.**", "pass")
def send_email(sender, cc_recipients, bcc_recipients, subject, body, attachments=None): """Send an email. All arguments should be Unicode strings (plain ASCII works as well). Only the real name part of sender and recipient addresses may contain non-ASCII characters. The email will be properly MIME encoded and delivered though SMTP to 172.17.0.1. This is easy to change if you want something different. The charset of the email will be the first one out of US-ASCII, ISO-8859-1 and UTF-8 that can represent all the characters occurring in the email. """ # combined recipients recipients = cc_recipients + bcc_recipients # Header class is smart enough to try US-ASCII, then the charset we # provide, then fall back to UTF-8. header_charset = 'ISO-8859-1' # We must choose the body charset manually for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8': try: body.encode(body_charset) except UnicodeError: pass else: break # Split real name (which is optional) and email address parts sender_name, sender_addr = parseaddr(sender) parsed_cc_recipients = [parseaddr(rec) for rec in cc_recipients] parsed_bcc_recipients = [parseaddr(rec) for rec in bcc_recipients] #recipient_name, recipient_addr = parseaddr(recipient) # We must always pass Unicode strings to Header, otherwise it will # use RFC 2047 encoding even on plain ASCII strings. sender_name = str(Header(str(sender_name), header_charset)) unicode_parsed_cc_recipients = [] for recipient_name, recipient_addr in parsed_cc_recipients: recipient_name = str(Header(str(recipient_name), header_charset)) # Make sure email addresses do not contain non-ASCII characters recipient_addr = recipient_addr.encode('ascii') unicode_parsed_cc_recipients.append((recipient_name, recipient_addr)) unicode_parsed_bcc_recipients = [] for recipient_name, recipient_addr in parsed_bcc_recipients: recipient_name = str(Header(str(recipient_name), header_charset)) # Make sure email addresses do not contain non-ASCII characters recipient_addr = recipient_addr.encode('ascii') unicode_parsed_bcc_recipients.append((recipient_name, recipient_addr)) # Make sure email addresses do not contain non-ASCII characters sender_addr = sender_addr.encode('ascii') # Create the message ('plain' stands for Content-Type: text/plain) msg = MIMEMultipart() msg['CC'] = COMMASPACE.join([ formataddr((recipient_name, recipient_addr)) for recipient_name, recipient_addr in unicode_parsed_cc_recipients ]) msg['BCC'] = COMMASPACE.join([ formataddr((recipient_name, recipient_addr)) for recipient_name, recipient_addr in unicode_parsed_bcc_recipients ]) msg['Subject'] = Header(str(subject), header_charset) msg['FROM'] = "*****@*****.**" msg.attach(MIMEText(body.encode(body_charset), 'plain', body_charset)) # Add attachments if isinstance(attachments, dict): for fname in attachments: part = MIMEBase('application', "octet-stream") part.set_payload(attachments[fname]) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % fname) msg.attach(part) # Send the message via SMTP to docker host smtp_url = "smtp://127.0.0.1:25" logger.info("smtp_url : %s" % smtp_url) smtp = SMTP("127.0.0.1") smtp.sendmail(sender, recipients, msg.as_string()) smtp.quit()
def send_email(): print "Send email report" config = get_config() cluster_name = flask.request.args.get('cluster_name', get_default_cluster()) path = flask.request.args.get('path', '/') start_date = flask.request.args.get('start_date', '2015-06-01') end_date = flask.request.args.get( 'end_date', datetime.datetime.now().strftime("%Y-%m-%d")) pdf_name = "qumulo-storage-report-%s-%s-%s-%s.pdf" % ( re.sub("[^a-z0-9]+", "_", cluster_name.lower()), re.sub("[^a-z0-9]+", "_", path.lower()), re.sub("[^a-z0-9]+", "", start_date.lower()), re.sub("[^a-z0-9]+", "", end_date.lower())) cmd = ["phantomjs", "phantom-screenshot.js"] qs = flask.request.query_string cmd.append(qs) cmd.append(pdf_name) print "Launch phantomjs" p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) out, err = p.communicate() print "phantomjs complete" username = config["email_account"]["account_username"] password = config["email_account"]["account_password"] fromaddr = config["email_account"]["from_email_address"] toaddrs = flask.request.args.get('to', '').replace(" ", "").split(",") text = "The latest Qumulo Daily Storage report is attached.<br />\r\n" text += "Cluster Name: <b>" + cluster_name + "</b><br />\r\n" text += "Path: <b>" + path + "</b><br />\r\n" text += "Start Date: <b>" + start_date + "</b><br />\r\n" text += "End Date: <b>" + end_date + "</b><br />\r\n<br />\r\n" subject = "Qumulo %s Storage Report %s to %s%s" % ( cluster_name, start_date, end_date, " For Path: " + path if path != "/" else "") html_message = text msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = fromaddr msg['To'] = ','.join(toaddrs) msg['Bcc'] = '' html = """\ <html> <head></head> <body> %s </body> </html> """ % (html_message) body = MIMEMultipart('alternative') part1 = MIMEText(re.sub("<[^>]+>", " ", text), 'plain') part2 = MIMEText(html, 'html') body.attach(part1) body.attach(part2) msg.attach(body) with open(pdf_name, "rb") as fil: attachFile = MIMEBase('application', 'pdf') attachFile.set_payload(fil.read()) Encoders.encode_base64(attachFile) attachFile.add_header('Content-Disposition', 'attachment', filename=os.path.basename(pdf_name)) msg.attach(attachFile) print "Connect to email server" if ":465" in config["email_account"]["server"]: smtp = smtplib.SMTP_SSL(config["email_account"]["server"]) else: smtp = smtplib.SMTP(config["email_account"]["server"]) print "Send email" smtp.ehlo() if username and password: smtp.login(username, password) smtp.sendmail(fromaddr, toaddrs, msg.as_string()) smtp.quit() print "Done send email" return out
def Envoi_mail(adresseExpediteur="", nomadresseExpediteur="", listeDestinataires=[], listeDestinatairesCCI=[], sujetMail="", texteMail="", listeFichiersJoints=[], serveur="localhost", port=None, avecAuthentification=False, avecStartTLS=False, listeImages=[], motdepasse=None, accuseReception=False, utilisateur=""): """ Envoi d'un mail avec pièce jointe """ import smtplib import poplib from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.MIMEImage import MIMEImage from email.MIMEAudio import MIMEAudio from email.Utils import COMMASPACE, formatdate from email import Encoders from email.utils import make_msgid import mimetypes assert type(listeDestinataires) == list assert type(listeFichiersJoints) == list # Corrige le pb des images embarquées index = 0 for img in listeImages: img = img.replace(u"\\", u"/") img = img.replace(u":", u"%3a") texteMail = texteMail.replace( _(u"file:/%s") % img, u"cid:image%d" % index) index += 1 # Création du message msg = MIMEMultipart('alternative') #msg['Message-ID'] = make_msgid() if accuseReception == True: msg['Disposition-Notification-To'] = adresseExpediteur # Conversion du HTML en plain text textePlain = UTILS_Html2text.html2text(texteMail) msg.attach(MIMEText(textePlain.encode('utf-8'), 'plain', 'utf-8')) msg.attach(MIMEText(texteMail.encode('utf-8'), 'html', 'utf-8')) # on encapsule dans un Multipart en mixed suplémentaire pour palier à la mauvaise detection de la piece jointe # par certains lecteurs mails tmpmsg = msg msg = MIMEMultipart('mixed') msg.attach(tmpmsg) # Ajout des headers à ce Multipart if nomadresseExpediteur == "" or nomadresseExpediteur == None: msg['From'] = adresseExpediteur else: msg['From'] = "\"%s\" <%s>" % (nomadresseExpediteur, adresseExpediteur) msg['To'] = ";".join(listeDestinataires) msg['Bcc'] = ";".join(listeDestinatairesCCI) msg['Date'] = formatdate(localtime=True) msg['Subject'] = sujetMail # Attache des pièces jointes for fichier in listeFichiersJoints: """Guess the content type based on the file's extension. Encoding will be ignored, altough we should check for simple things like gzip'd or compressed files.""" ctype, encoding = mimetypes.guess_type(fichier) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compresses), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': fp = open(fichier) # Note : we should handle calculating the charset part = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == 'image': fp = open(fichier, 'rb') part = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = open(fichier, 'rb') part = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(fichier, 'rb') part = MIMEBase(maintype, subtype) part.set_payload(fp.read()) fp.close() # Encode the payload using Base64 Encoders.encode_base64(part) # Set the filename parameter nomFichier = os.path.basename(fichier) if type(nomFichier) == unicode: nomFichier = FonctionsPerso.Supprime_accent(nomFichier) # changement cosmetique pour ajouter les guillements autour du filename part.add_header('Content-Disposition', "attachment; filename=\"%s\"" % nomFichier) msg.attach(part) # Images incluses index = 0 for img in listeImages: fp = open(img, 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<image%d>' % index) msgImage.add_header('Content-Disposition', 'inline', filename=img) msg.attach(msgImage) index += 1 ## Certains SMTP (exemple Orange Pro) demandent une authentifcation (en général user : boite mail et pwd : mot de passe associé au smtp sécurisé ) ## mais ne supportent pas le mode starttls ## Ces identifiants sont généralement utilisés lors d'un envoi de mail abec un FAI différent du propriétaire du SMTP ## Par exemple pour envoyer un mail avec le smtp pro orange depuis un autre FAI (Free, SFR....) ## serveur : smtp.premium.orange.fr - port 587 ## user : [email protected] ## pwd : mon_pwd ## On positionne dans ce cas le parametre avecAuthentification a True ## et le parametre avecStartTLS est positionné selon l'état du support de la fonction startTLS par le SMTP if motdepasse == None: motdepasse = "" if utilisateur == None: utilisateur = "" if avecAuthentification in (0, False, None): # Envoi standard smtp = smtplib.SMTP(serveur, timeout=150) else: # Si identification SSL nécessaire : smtp = smtplib.SMTP(serveur, port, timeout=150) smtp.ehlo() if avecStartTLS == True: smtp.starttls() smtp.ehlo() smtp.login(utilisateur.encode('utf-8'), motdepasse.encode('utf-8')) smtp.sendmail(adresseExpediteur, listeDestinataires + listeDestinatairesCCI, msg.as_string()) smtp.close() return True
def send_distribution_list(obj, event): if not event.new_state.id in ['internally_published']: return #other all_email = list() report_authors = obj.report_author mission_members = get_mission(obj).mission_members mission_distribution = obj.mission_distribution #creator creator = obj.Creator() creator_info = obj.portal_membership.getMemberInfo(creator) creator_full_name = creator_info['fullname'] for i in set(report_authors + mission_members + [creator]): email = obj.portal_membership.getMemberById(i).getProperty('email') all_email.append(email) all_email.extend(mission_distribution) filtered_email = list(set(all_email)) converter = getUtility(IPDFConverter) pdf = converter.convert(obj) mailhost = obj.MailHost if not mailhost: raise ComponentLookupError('You must have a Mailhost utility to' 'execute this action') from_address = obj.email_from_address if not from_address: raise ValueError('You must provide a source address for this' 'action or enter an email in the portal properties') from_name = obj.email_from_name source = "%s <%s>" % (from_name, from_address) event_title = safe_unicode(safe_unicode(obj.Title())) subject = event_title msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = source body = """You can view the full report online at: %(url)s -- This is a system message from %(site_name)s. """ % { 'url': obj.absolute_url(), 'site_name': getSite().title } body_safe = body.encode('utf-8') htmlPart = MIMEText(body_safe, 'plain', 'utf-8') msg.attach(htmlPart) # generated pdf attachments attachment = MIMEBase('application', 'pdf') attachment.set_payload(pdf.buf) Encoders.encode_base64(attachment) attachment.add_header('Content-Disposition', 'attachment', filename=subject + '.pdf') msg.attach(attachment) #attactments in the report file_brains = obj.getFolderContents() for file_brain in file_brains: file = file_brain.getObject().getFile() ctype = file.getContentType() filename = file.filename maintype, subtype = ctype.split(('/'), 1) attachment = MIMEBase(maintype, subtype) attachment.set_payload(str(file)) Encoders.encode_base64(attachment) attachment.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(attachment) #send email for recipient in filtered_email: # skip broken recipients if not recipient: continue if '@' not in recipient: continue del msg['To'] msg['To'] = recipient mailhost.send(msg.as_string())
def send_mail(self, cr, uid, ids, addresses, subject='', body=None, payload=None, message_id=None, context=None): #TODO: Replace all this with a single email object if body is None: body = {} if payload is None: payload = {} if context is None: context = {} logger = netsvc.Logger() for id in ids: core_obj = self.browse(cr, uid, id, context) serv = self.smtp_connection(cr, uid, id) if serv: try: # Prepare multipart containers depending on data text_subtype = (core_obj.send_pref == 'alternative' ) and 'alternative' or 'mixed' # Need a multipart/mixed wrapper for attachments if content is alternative if payload and text_subtype == 'alternative': payload_part = MIMEMultipart(_subtype='mixed') text_part = MIMEMultipart(_subtype=text_subtype) payload_part.attach(text_part) else: # otherwise a single multipart/mixed will do the whole job payload_part = text_part = MIMEMultipart( _subtype=text_subtype) if subject: payload_part['Subject'] = subject from_email = core_obj.email_id if '<' in from_email: # We have a structured email address, keep it untouched payload_part['From'] = Header(core_obj.email_id, 'utf-8').encode() else: # Plain email address, construct a structured one based on the name: sender_name = Header(core_obj.name, 'utf-8').encode() payload_part[ 'From'] = sender_name + " <" + core_obj.email_id + ">" payload_part['Organization'] = tools.ustr( core_obj.user.company_id.name) payload_part['Date'] = formatdate() addresses_l = extract_emails_from_dict(addresses) if addresses_l['To']: payload_part['To'] = u','.join(addresses_l['To']) if addresses_l['CC']: payload_part['CC'] = u','.join(addresses_l['CC']) if addresses_l['Reply-To']: payload_part['Reply-To'] = addresses_l['Reply-To'][0] if message_id: payload_part['Message-ID'] = message_id if body.get('text', False): temp_body_text = body.get('text', '') l = len( temp_body_text.replace(' ', '').replace( '\r', '').replace('\n', '')) if l == 0: body['text'] = u'No Mail Message' # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. if core_obj.send_pref in ('text', 'mixed', 'alternative'): body_text = body.get('text', u'<Empty Message>') body_text = tools.ustr(body_text) text_part.attach( MIMEText(body_text.encode("utf-8"), _charset='UTF-8')) if core_obj.send_pref in ('html', 'mixed', 'alternative'): html_body = body.get('html', u'') if len(html_body) == 0 or html_body == u'': html_body = body.get( 'text', u'<p><Empty Message></p>').replace( '\n', '<br/>').replace('\r', '<br/>') html_body = tools.ustr(html_body) text_part.attach( MIMEText(html_body.encode("utf-8"), _subtype='html', _charset='UTF-8')) #Now add attachments if any, wrapping into a container multipart/mixed if needed if payload: for file in payload: part = MIMEBase('application', "octet-stream") part.set_payload(base64.decodestring( payload[file])) part.add_header('Content-Disposition', 'attachment; filename="%s"' % file) Encoders.encode_base64(part) payload_part.attach(part) except Exception, error: logger.notifyChannel( _("Email Template"), netsvc.LOG_ERROR, _("Mail from Account %s failed. Probable Reason:MIME Error\nDescription: %s" ) % (id, tools.ustr(error))) return { 'error_msg': _("Server Send Error\nDescription: %s") % error } try: serv.sendmail(payload_part['From'], addresses_l['all-recipients'], payload_part.as_string()) except Exception, error: logging.getLogger('email_template').error(_( "Mail from Account %s failed. Probable Reason: Server Send Error\n Description: %s" ), id, tools.ustr( error), exc_info=True) return { 'error_msg': _("Server Send Error\nDescription: %s") % tools.ustr(error) } #The mail sending is complete serv.close() logger.notifyChannel( _("Email Template"), netsvc.LOG_INFO, _("Mail from Account %s successfully Sent.") % (id)) return True
def email(self, subject, body): try: # Start send mail code - provided by flofrihandy, modified by peg msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = self.cfg.get(['output-email', 'from']) msg['To'] = self.cfg.get(['output-email', 'to']) file_found = False timeout = 0 while not file_found: if not os.path.isfile(body): timeout += 1 time.sleep(1) else: file_found = True if timeout == 30: break if file_found: time.sleep(2) fp = open(body, 'rb') msg_text = MIMEText(fp.read()) fp.close() msg.attach(msg_text) for tty in self.ttyFiles: fp = open(tty, 'rb') logdata = MIMEBase('application', "octet-stream") logdata.set_payload(fp.read()) fp.close() Encoders.encode_base64(logdata) logdata.add_header('Content-Disposition', 'attachment', filename=os.path.basename(tty)) msg.attach(logdata) s = smtplib.SMTP(self.cfg.get(['output-email', 'host']), self.cfg.getint(['output-email', 'port'])) username = self.cfg.get(['output-email', 'username']) password = self.cfg.get(['output-email', 'password']) if len(username) > 0 and len(password) > 0: s.ehlo() if self.cfg.getboolean(['output-email', 'use_tls']): s.starttls() if self.cfg.getboolean(['output-email', 'use_smtpauth']): s.login(username, password) s.sendmail(msg['From'], msg['To'].split(','), msg.as_string()) s.quit() # End send mail code except Exception, ex: log.msg(log.LRED, '[PLUGIN][EMAIL][ERR]', str(ex))
email = salary_sheet_sum_cell(row=row, column=email_col_pos).value if not email: print('no email address configed') continue msgRoot['To'] = email #content msText = MIMEText(content, _subtype='plain', _charset='utf-8') msgRoot.attach(msText) #attachment maintype = 'application' subtype = 'octet-stream' att = MIMEBase(maintype, subtype) att.set_payload(open(salary_filename_full, 'rb').read()) Encoders.encode_base64(att) #att["Content-Disposition"] = 'attachment; filename= %s'%Header(u'工资明细.xlsx','UTF-8') att["Content-Disposition"] = u'attachment; filename=工资明细.xlsx'.encode( 'gbk') #print('attachment:' + att["Content-Disposition"]) msgRoot.attach(att) send_mail_sum += 1 print('send mail to:' + name + "; To:" + email + ',No:%d' % send_mail_sum) smtp.sendmail(sender, email, msgRoot.as_string()) #avoid to be recoginized as spam by email server time.sleep(random.randint(1, 3)) send_mail_count = send_mail_count + 1
def send_mail(send_from, send_to, subject, text, files=None, data_attachments=None, server="smtp.office365.com", port=587, tls=True, html=False, images=None, username=None, password=None, config_file=None, config=None): if files is None: files = [] if images is None: images = [] if data_attachments is None: data_attachments = [] if config_file is not None: config = ConfigParser.ConfigParser() config.read(config_file) if config is not None: server = config.get('smtp', 'server') port = config.get('smtp', 'port') tls = config.get('smtp', 'tls').lower() in ('true', 'yes', 'y') username = config.get('smtp', 'username') password = config.get('smtp', 'password') msg = MIMEMultipart('related') msg['From'] = send_from msg['To'] = send_to if isinstance(send_to, basestring) else COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text, 'html' if html else 'plain')) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload(open(f, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) for f in data_attachments: part = MIMEBase('application', "octet-stream") part.set_payload(f['data']) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % f['filename']) msg.attach(part) for (n, i) in enumerate(images): fp = open(i, 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<image{0}>'.format(str(n + 1))) msg.attach(msgImage) smtp = smtplib.SMTP(server, int(port)) if tls: smtp.starttls() if username is not None: smtp.login(username, password) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
f"Dear {recipient_name},<br> <br> That is a first sketch for the cover of the future reports .<br> The Pdf attached and the email have been created via a script in Python to simulate the report creation :) <br> regards,<br><br> Giulia" ) msg.attach(MIMEText(emailcontent, _subtype='html')) # Attach a file mail_file = MIMEBase('application', 'pdf') mail_file.set_payload( open( 'Pilot Element ' + start_pv.strftime(' %B %Y ') + ' Performance Overview.pdf', 'rb').read()) mail_file.add_header('Content-Disposition', 'attachment', filename='Pilot Element ' + start_pv.strftime(' %B %Y ') + ' Performance Overview.pdf') Encoders.encode_base64(mail_file) msg.attach(mail_file) email_from = "*****@*****.**" email_to1 = "*****@*****.**" email_subject = 'New report cover' smtp_server = 'smtp.gmail.com' smtp_port = 587 smtp_username = "******" smtp_password = "******" server = smtplib.SMTP(smtp_server, smtp_port) server.starttls() server.login(smtp_username, smtp_password)
#caminho do arquivo: caminho_arquivo = 'caminho-do-arquivi/anexo.pdf' #servidor SMTP: smtp_server = 'smtp.gmail.com' smtp_server_port = '587' #Assunto e corpo do email: msg = MIMEMultipart() msg['Subject'] = "Assunto" body = ''' Corpo do texto ''' msg.attach(MIMEText(body, 'plain')) #Anexo do e-mail: msg_file = MIMEBase('application', 'pdf') msg_file.set_payload(file(caminho_arquivo).read()) Encoders.encode_base64(msg_file) msg_file.add_header('Content-Disposition', 'attachment', filename='anexo.pdf') msg.attach(msg_file) #processo mailer = smtplib.SMTP(smtp_server, smtp_server_port) mailer.ehlo() mailer.starttls() mailer.login(email_login, senha) mailer.sendmail(email_login, send_mail_to, msg.as_string()) print('E-mail enviado com sucesso !') mailer.close()
def send_email(self, recipients, subject, message, consultants, cc): portal_url = getToolByName(self.context, 'portal_url') portal_catalog = getToolByName(self.context, 'portal_catalog') portal_state = getMultiAdapter((self.context, self.request), name=u"plone_portal_state") portal = portal_url.getPortalObject() mFrom = portal.getProperty('email_from_address') statusmessages = IStatusMessage(self.request) mailhost = self.context.MailHost from_address = api.user.get_current().getProperty('email') msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = '%s <%s>' % (portal_state.portal_title(), mFrom) htmlPart = MIMEText(message, 'plain', 'utf-8') msg.attach(htmlPart) zipped = [] timestr = time.strftime("%Y%m%d-%H%M%S") if consultants: brains = portal_catalog.unrestrictedSearchResults(portal_type='ploneun.consultant.consultant', UID=consultants) uploaded_files = [] for brain in brains: brains2 = portal_catalog.unrestrictedSearchResults(path={'query':brain.getPath(), 'depth':1}, portal_type='File') for brain2 in brains2: obj2 = brain2._unrestrictedGetObject() if obj2.getFile(): uploaded_files.append({'file': obj2.getFile().getBlob().open().name, 'filename':obj2.getFile().filename}) if uploaded_files: zf = zipfile.ZipFile("/tmp/%s.zip" % timestr, "w", zipfile.ZIP_DEFLATED) for uf in uploaded_files: zf.write(uf['file'], uf['filename']) zf.close() attachment = MIMEBase('application', 'zip') attachment.set_payload(open(zf.filename).read()) open(zf.filename).close() Encoders.encode_base64(attachment) attachment.add_header('Content-Disposition', 'attachment', filename='consultant-cvs' + '.zip') msg.attach(attachment) msg['To'] = ','.join(recipients) msg['cc'] = ','.join(cc) mailhost.send(msg.as_string()) #for recipient in recipients: # # skip broken recipients # if not recipient: # continue # if '@' not in recipient: # continue # del msg['To'] # msg['To'] = recipient # mailhost.send(msg.as_string()) for f in os.listdir('/tmp/'): if timestr+'.zip' == f: os.remove('/tmp/'+f) statusmessages.add('Emails sent') self.request.response.redirect(self.context.absolute_url())
def mail(to, subject, text, attach, prioflag1, prioflag2): msg = MIMEMultipart() msg['From'] = str( Header(from_displayname, 'UTF-8').encode() + ' <' + from_address + '> ') msg['To'] = to msg['X-Priority'] = prioflag1 msg['X-MSMail-Priority'] = prioflag2 msg['Subject'] = Header(subject, 'UTF-8').encode() # specify if its html or plain # body message here body_type = MIMEText(text, "%s" % (message_flag), 'UTF-8') msg.attach(body_type) # define connection mimebase part = MIMEBase('application', 'octet-stream') part.set_payload(open(attach, 'rb').read()) # base 64 encode message mimebase Encoders.encode_base64(part) # add headers part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attach)) msg.attach(part) io = StringIO() msggen = Generator(io, False) msggen.flatten(msg) # define connection to smtp server mailServer = smtplib.SMTP(smtp, int(port)) mailServer.ehlo() # send ehlo to smtp server if sendmail == 0: if email_provider == "gmail" or email_provider == "yahoo": mailServer.ehlo() # start TLS needed for gmail and yahoo and hotmail (live) try: mailServer.starttls() except: pass mailServer.ehlo() if counter == 0: try: if email_provider == "gmail" or email_provider == "yahoo" or email_provider == "hotmail": try: mailServer.starttls() except: pass mailServer.ehlo() if len(provideruser) > 0: mailServer.login(provideruser, pwd) mailServer.sendmail(from_address, to, io.getvalue()) except Exception as e: print_error( "Unable to deliver email. Printing exceptions message below, this is most likely due to an illegal attachment. If using GMAIL they inspect PDFs and is most likely getting caught." ) input("Press {return} to view error message.") print(str(e)) try: mailServer.docmd("AUTH LOGIN", base64.b64encode(provideruser)) mailServer.docmd(base64.b64encode(pwd), "") except Exception as e: print(str(e)) try: mailServer.login(provideremail, pwd) thread.start_new_thread( mailServer.sendmail(from_address, to, io.getvalue())) except Exception as e: return_continue() if email_provider == "hotmail": mailServer.login(provideruser, pwd) thread.start_new_thread(mailServer.sendmail, (from_address, to, io.getvalue())) if sendmail == 1: thread.start_new_thread(mailServer.sendmail, (from_address, to, io.getvalue()))
def mail(to, subject, text, cc=None, bcc=None, reply_to=None, attach=None, html=None, pre=False, custom_headers=None): msg = MIMEMultipart() msg['From'] = full_name + " <" + email_addr + ">" msg['To'] = to msg['Subject'] = subject to = [to] if cc: # cc gets added to the text header as well as list of recipients if type(cc) in [str, unicode]: msg.add_header('Cc', cc) cc = [cc] else: cc = ', '.join(cc) msg.add_header('Cc', cc) to += cc if bcc: # bcc does not get added to the headers, but is a recipient if type(bcc) in [str, unicode]: bcc = [bcc] to += bcc if reply_to: msg.add_header('Reply-To', reply_to) # Encapsulate the plain and HTML versions of the message body in an # 'alternative' part, so message agents can decide which they want to # display. if pre: html = "<pre>%s</pre>" % text if html: msgAlternative = MIMEMultipart('alternative') msg.attach(msgAlternative) msgText = MIMEText(text) msgAlternative.attach(msgText) # We reference the image in the IMG SRC attribute by the ID we give it # below msgText = MIMEText(html, 'html') msgAlternative.attach(msgText) else: msg.attach(MIMEText(text)) if attach: 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) if custom_headers: for k, v in custom_headers.iteritems(): msg.add_header(k, v) mailServer = smtplib.SMTP(smtp_server, 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(email_addr, email_pw) mailServer.sendmail(email_addr, to, msg.as_string()) # Should be mailServer.quit(), but that crashes... mailServer.close()
def send(self): """ Send the email message represented by this object. """ # Validate message if self._textBody is None and self._htmlBody is None: raise Exception( "Error! Must specify at least one body type (HTML or Text)") if len(self._to) == 0: raise Exception("Must specify at least one recipient") # Create the message part if self._textBody is not None and self._htmlBody is None: msg = MIMEText(self._textBody, "plain") elif self._textBody is None and self._htmlBody is not None: msg = MIMEText(self._htmlBody, "html") else: msg = MIMEMultipart("alternative") msg.attach(MIMEText(self._textBody, "plain")) msg.attach(MIMEText(self._htmlBody, "html")) # Add attachments, if any if len(self._attach) != 0: tmpmsg = msg msg = MIMEMultipart() msg.attach(tmpmsg) for fname, attachname in self._attach: if not os.path.exists(fname): raise Exception( "File '{0}' does not exist. Not attaching to email.". format(fname)) continue if not os.path.isfile(fname): raise Exception( "Attachment '{0}' is not a file. Not attaching to email.". format(fname)) continue # Guess at encoding type ctype, encoding = mimetypes.guess_type(fname) if ctype is None or encoding is not None: # No guess could be made so use a binary type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': fp = open(fname) attach = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == 'image': fp = open(fname, 'rb') attach = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = open(fname, 'rb') attach = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(fname, 'rb') attach = MIMEBase(maintype, subtype) attach.set_payload(fp.read()) fp.close() # Encode the payload using Base64 encoders.encode_base64(attach) # Set the filename parameter if attachname is None: filename = os.path.basename(fname) else: filename = attachname attach.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(attach) # Complete header # This is where To, CC, BCC are differentiated msg['Subject'] = self._subject msg['From'] = self._from msg['To'] = ", ".join(self._to) msg['CC'] = ", ".join(self._cc) msg['BCC'] = ", ".join(self._bcc) if self._replyTo is not None: msg['reply-to'] = self._replyTo msg.preamble = "You need a MIME enabled mail reader to see this message" msg = msg.as_string() allRecipients = self._to + self._cc + self._bcc # Send message try: server = smtplib.SMTP(self._smtpServer, self._smtpPort, self._hostname, 5) server.set_debuglevel(self._debugLevel) server.ehlo() if self._username: if server.has_extn('STARTTLS'): server.starttls() else: server.quit() server = smtplib.SMTP_SSL(self._smtpServer, self._smtpPort, self._hostname) server.set_debuglevel(self._debugLevel) server.ehlo() # re-identify ourselves over secure connection server.login(self._username, self._password) result = server.sendmail(self._from, allRecipients, msg) except Exception, err: raise err
def inviamail(app=None, mailfrom='', mailto=None, files=None, cc=None, bcc=None, \ server = None, auth_required=False, username='', password=None, \ subject='', mail_format=None, html_text='', plaintext_text='', \ blacklist=None, passwd_force_ask=False, dry_send=False): if mailto is None: mailto = [] elif ',' in mailto: mailto = mailto.split(',') elif isinstance(mailto, str): mailto = [mailto] else: raise ValueError('Wrong mailto recipient: {}'.format(mailto)) if files is None: files = [] if cc is None: cc = [] if bcc is None: bcc = [] if blacklist is None: blacklist = [] logger.debug("files: %s" % files) assert isinstance(files, list) logger.debug("cc: %s" % cc) assert isinstance(cc, list) logger.debug("bcc: %s" % bcc) assert isinstance(bcc, list) logger.debug("auth_required: %s" % auth_required) assert isinstance(auth_required, bool) logger.debug("passwd_force_ask: %s" % passwd_force_ask) assert isinstance(passwd_force_ask, bool) logger.debug("dry_send: %s" % dry_send) assert isinstance(dry_send, bool) logger.debug("mail_format: %s" % mail_format) assert mail_format in AVAILABLE_FORMATS # Record the MIME types of both parts - text/plain and text/html. logger.debug("mailto: %s" % mailto) logger.debug("cc: %s" % cc) logger.debug("bcc: %s" % bcc) mailto = set(mailto) cc = set(cc) bcc = set(bcc) mailto.difference_update(blacklist) cc.difference_update(blacklist) bcc.difference_update(blacklist) mailto = list(mailto) cc = list(cc) bcc = list(bcc) # Bug that I forgot to fix from 6 years ago: # https://forum.mozillaitalia.org/index.php?topic=49084.0 # The primary MIME type of the message must be 'mixed' and # not 'alternative' message = MIMEMultipart('mixed') message['From'] = mailfrom message['To'] = COMMASPACE.join(mailto) message['Date'] = formatdate(localtime=True) message['Subject'] = subject message['Cc'] = COMMASPACE.join(cc) message['Bcc'] = COMMASPACE.join(bcc) # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. ATTACH[mail_format](message, html_text, plaintext_text) for f in files: part = MIMEBase('application', 'octet-stream') part.set_payload(open(f, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) message.attach(part) mailto = list(mailto) mailto.extend(cc) mailto.extend(bcc) addresses = list(set(mailto)) #print message.as_string() msg = """ EMAIL SUMMARY Email will be sent to: %s file attached: %s """ % (', '.join(addresses), ', '.join(files)) logger.info(msg) try: smtp = smtplib.SMTP(server) smtp.ehlo() except ConnectionError(server): logger.error("Errore nella connessione al server") return -1 if auth_required: smtp.starttls() if password == None or not auth(smtp, username, password) or passwd_force_ask: while 1: password = getpass.getpass("Password:"******"Login avvenuto correttamente") if not dry_send: smtp.sendmail(mailfrom, addresses, message.as_string()) smtp.close() logger.info("Email inviata correttamente") return 0
def bot(): global args global base_path # -s HOST="irc.freenode.net" if (args.server): HOST=args.server # -p PORT=6667 if (args.port): PORT=args.port # -n NICK="IRC_Bot" if (args.nick): NICK=args.nick # -i IDENT="bot" if (args.ident): IDENT=args.ident # -r REALNAME="IRC Bot" if (args.real): REALNAME=args.real # -c CHANNEL="irclib" if (args.channel): CHANNEL=args.channel #server connect IRCsocket=socket.socket() IRCsocket.connect((HOST, PORT)) IRCsocket.send("NICK %s\r\n" % NICK) IRCsocket.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME)) IRCsocket.send("JOIN #%s\r\n" % CHANNEL) database = os.path.dirname(base_path) + "log.db" db = use_plugin(args.plugin, os.path.dirname(base_path)) if not isfile(database): db.create(database) buffer = "" online = set() while 1: buffer=buffer + IRCsocket.recv(1024) irc=string.split(buffer, "\n") buffer=irc.pop() for msg in irc: msg=string.rstrip(msg) msg=string.split(msg) print msg if(msg[0]=="PING"): IRCsocket.send("PONG %s\r\n" % msg[1]) elif ((msg[1] == "PRIVMSG") & (msg[2] == NICK)): db.add(database, msg[1], msg[0].split("!")[0][1:], " ".join(msg[3:])) if (msg[3][1:] == "mail"): if args.m_address: if args.m_server: if len(msg) > 3: mail = MIMEMultipart() mail["From"] = args.m_address mail["To"] = msg[4] mail["Subject"] = "IRC Log" mail['Date'] = formatdate(localtime=True) part = MIMEBase('application', "octet-stream") part.set_payload( open(database,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(database)) mail.attach(part) server = smtplib.SMTP(args.m_server) if args.m_username: if args.m_password: server.login(args.m_username, args.m_password) try: failed = server.sendmail(args.m_address, msg[4], mail.as_string()) server.close() except Exception, e: errorMsg = "Unable to send email. Error: %s" % str(e) elif (msg[3][1:] == "when"): if len(msg) > 3: if msg[4] in online: IRCsocket.send("PRIVMSG %s :%s is now online\r\n" % (msg[0].split("!")[0][1:], msg[4])) else: IRCsocket.send("PRIVMSG %s :%s was last seen %s\r\n" % (msg[0].split("!")[0][1:], msg[4], db.seen(database, msg[4]))) elif (msg[1] == "JOIN"): db.add(database, msg[1], msg[0].split("!")[0][1:], msg[2]) online.add(msg[0].split("!")[0][1:]) elif (msg[1] == "PART"): db.add(database, msg[1], msg[0].split("!")[0][1:], msg[2]) online.discard(msg[0].split("!")[0][1:])
def email_send(email_from, email_to, subject, body, email_cc=None, email_bcc=None, reply_to=False, attach=None, openobject_id=False, ssl=False, debug=False, subtype='plain', x_headers=None, priority='3'): """Send an email. Arguments: `email_from`: A string used to fill the `From` header, if falsy, config['email_from'] is used instead. Also used for the `Reply-To` header if `reply_to` is not provided `email_to`: a sequence of addresses to send the mail to. """ if x_headers is None: x_headers = {} if not (email_from or config['email_from']): raise ValueError("Sending an email requires either providing a sender " "address or having configured one") if not email_from: email_from = config.get('email_from', False) if not email_cc: email_cc = [] if not email_bcc: email_bcc = [] if not body: body = u'' try: email_body = body.encode('utf-8') except (UnicodeEncodeError, UnicodeDecodeError): email_body = body try: email_text = MIMEText(email_body.encode('utf8') or '',_subtype=subtype,_charset='utf-8') except: email_text = MIMEText(email_body or '',_subtype=subtype,_charset='utf-8') if attach: msg = MIMEMultipart() else: msg = email_text msg['Subject'] = Header(ustr(subject), 'utf-8') msg['From'] = email_from del msg['Reply-To'] if reply_to: msg['Reply-To'] = reply_to else: msg['Reply-To'] = msg['From'] msg['To'] = COMMASPACE.join(email_to) if email_cc: msg['Cc'] = COMMASPACE.join(email_cc) if email_bcc: msg['Bcc'] = COMMASPACE.join(email_bcc) msg['Date'] = formatdate(localtime=True) msg['X-Priority'] = priorities.get(priority, '3 (Normal)') # Add dynamic X Header for key, value in x_headers.iteritems(): msg['%s' % key] = str(value) if attach: msg.attach(email_text) for (fname,fcontent) in attach: part = MIMEBase('application', "octet-stream") part.set_payload( fcontent ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % (fname,)) msg.attach(part) class WriteToLogger(object): def __init__(self): self.logger = netsvc.Logger() def write(self, s): self.logger.notifyChannel('email_send', netsvc.LOG_DEBUG, s) return _email_send(email_from, flatten([email_to, email_cc, email_bcc]), msg, openobject_id=openobject_id, ssl=ssl, debug=debug)
def message(self): from ..utils import get_attachment_filename_from_url, replace_cid_and_change_headers to = anyjson.loads(self.to) cc = anyjson.loads(self.cc) bcc = anyjson.loads(self.bcc) if self.send_from.from_name: # Add account name to From header if one is available from_email = '"%s" <%s>' % (Header( u'%s' % self.send_from.from_name, 'utf-8'), self.send_from.email_address) else: # Otherwise only add the email address from_email = self.send_from.email_address html, text, inline_headers = replace_cid_and_change_headers( self.body, self.original_message_id) email_message = SafeMIMEMultipart('related') email_message['Subject'] = self.subject email_message['From'] = from_email if to: email_message['To'] = ','.join(list(to)) if cc: email_message['cc'] = ','.join(list(cc)) if bcc: email_message['bcc'] = ','.join(list(bcc)) email_message_alternative = SafeMIMEMultipart('alternative') email_message.attach(email_message_alternative) email_message_text = SafeMIMEText(text, 'plain', 'utf-8') email_message_alternative.attach(email_message_text) email_message_html = SafeMIMEText(html, 'html', 'utf-8') email_message_alternative.attach(email_message_html) for attachment in self.attachments.all(): if attachment.inline: continue try: storage_file = default_storage._open( attachment.attachment.name) except IOError: logger.exception('Couldn\'t get attachment, not sending %s' % self.id) return False filename = get_attachment_filename_from_url( attachment.attachment.name) storage_file.open() content = storage_file.read() storage_file.close() content_type, encoding = mimetypes.guess_type(filename) if content_type is None or encoding is not None: content_type = 'application/octet-stream' main_type, sub_type = content_type.split('/', 1) if main_type == 'text': msg = MIMEText(content, _subtype=sub_type) elif main_type == 'image': msg = MIMEImage(content, _subtype=sub_type) elif main_type == 'audio': msg = MIMEAudio(content, _subtype=sub_type) else: msg = MIMEBase(main_type, sub_type) msg.set_payload(content) Encoders.encode_base64(msg) msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(filename)) email_message.attach(msg) # Add the inline attachments to email message header for inline_header in inline_headers: main_type, sub_type = inline_header['content-type'].split('/', 1) if main_type == 'image': msg = MIMEImage(inline_header['content'], _subtype=sub_type, name=os.path.basename( inline_header['content-filename'])) msg.add_header('Content-Disposition', inline_header['content-disposition'], filename=os.path.basename( inline_header['content-filename'])) msg.add_header('Content-ID', inline_header['content-id']) email_message.attach(msg) return email_message
def send_mail(to, subject, text, attachments=[], cc=[], bcc=[], smtphost="", fromaddr=""): if sys.version_info[0] == 2: from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders else: from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email.utils import COMMASPACE, formatdate from email import encoders as Encoders from string import Template import socket import smtplib if not isinstance(to, list): print("the 'to' parameter needs to be a list") return False if len(to) == 0: print("no 'to' email addresses") return False myhost = socket.getfqdn() if smtphost == '': smtphost = get_mx_from_email_or_fqdn(myhost) if not smtphost: sys.stderr.write('could not determine smtp mail host !\n') if fromaddr == '': fromaddr = os.path.basename(__file__) + '-no-reply@' + \ '.'.join(myhost.split(".")[-2:]) #extract domain from host tc = 0 for t in to: if '@' not in t: # if no email domain given use domain from local host to[tc] = t + '@' + '.'.join(myhost.split(".")[-2:]) tc += 1 message = MIMEMultipart() message['From'] = fromaddr message['To'] = COMMASPACE.join(to) message['Date'] = formatdate(localtime=True) message['Subject'] = subject message['Cc'] = COMMASPACE.join(cc) message['Bcc'] = COMMASPACE.join(bcc) body = Template('This is a notification message from $application, running on \n' + \ 'host $host. Please review the following message:\n\n' + \ '$notify_text\n\nIf output is being captured, you may find additional\n' + \ 'information in your logs.\n' ) host_name = socket.gethostname() full_body = body.substitute(host=host_name.upper(), notify_text=text, application=os.path.basename(__file__)) message.attach(MIMEText(full_body)) for f in attachments: part = MIMEBase('application', 'octet-stream') part.set_payload(open(f, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) message.attach(part) addresses = [] for x in to: addresses.append(x) for x in cc: addresses.append(x) for x in bcc: addresses.append(x) smtp = smtplib.SMTP(smtphost) smtp.sendmail(fromaddr, addresses, message.as_string()) smtp.close() return True
def render_email(from_email, to, subject, text_template=None, html_template=None, cc=None, attachments=None, **context): """ Read the templates for email messages, format them, construct the email from them and return the corresponding email message object. :param from_email: Email From :param to: Email IDs of direct recepients :param subject: Email subject :param text_template: <Text email template path> :param html_template: <HTML email template path> :param cc: Email IDs of Cc recepients :param attachments: A dict of filename:string as key value pair [preferable file buffer streams] :param context: Context to be sent to template rendering :return: Email multipart instance or Text/HTML part """ if not (text_template or html_template): raise Exception("Atleast HTML or TEXT template is required") # Create the body of the message (a plain-text and an HTML version). # text is your plain-text email # html is your html version of the email # if the reciever is able to view html emails then only the html # email will be displayed if attachments: msg = MIMEMultipart('mixed') else: msg = MIMEMultipart('alternative') if text_template: if isinstance(text_template, Template): text = text_template.render(**context) else: text = unicode(render_template(text_template, **context)) text_part = MIMEText(text.encode("utf-8"), 'plain', _charset="UTF-8") msg.attach(text_part) if html_template: if isinstance(html_template, Template): html = html_template.render(**context) else: html = unicode(render_template(html_template, **context)) html_part = MIMEText(html.encode("utf-8"), 'html', _charset="UTF-8") msg.attach(html_part) if text_template and not (html_template or attachments): msg = text_part elif html_template and not (text_template or attachments): msg = html_part if attachments: for filename, content in attachments.items(): part = MIMEBase('application', "octet-stream") part.set_payload(content) Encoders.encode_base64(part) # XXX: Filename might have to be encoded with utf-8, # i.e., part's encoding or with email's encoding part.add_header('Content-Disposition', 'attachment; filename="%s"' % filename) msg.attach(part) # We need to use Header objects here instead of just assigning the strings # in order to get our headers properly encoded (with QP). msg['Subject'] = Header(subject) msg['From'] = Header(from_email) msg['To'] = Header(to) if cc: msg['Cc'] = Header(cc) return msg
def build_email(self, email_from, email_to, subject, body, email_cc=None, email_bcc=None, reply_to=False, attachments=None, message_id=None, references=None, object_id=False, subtype='plain', headers=None, body_alternative=None, subtype_alternative='plain'): """ copy-pasted from openerp/addons/base/ir/ir_mail_server.py::build_email """ ftemplate = '__image-%s__' fcounter = 0 attachments = attachments or [] pattern = re.compile(r'"data:image/png;base64,[^"]*"') pos = 0 new_body = '' while True: match = pattern.search(body, pos) if not match: break s = match.start() e = match.end() data = body[s + len('"data:image/png;base64,'):e - 1] new_body += body[pos:s] fname = ftemplate % fcounter fcounter += 1 attachments.append((fname, base64.b64decode(data))) new_body += '"cid:%s"' % fname pos = e new_body += body[pos:] body = new_body email_from = email_from or tools.config.get('email_from') assert email_from, "You must either provide a sender address explicitly or configure "\ "a global sender address in the server configuration or with the "\ "--email-from startup parameter." # Note: we must force all strings to to 8-bit utf-8 when crafting message, # or use encode_header() for headers, which does it automatically. headers = headers or {} # need valid dict later if not email_cc: email_cc = [] if not email_bcc: email_bcc = [] if not body: body = u'' email_body_utf8 = ustr(body).encode('utf-8') email_text_part = MIMEText(email_body_utf8, _subtype=subtype, _charset='utf-8') msg = MIMEMultipart() if not message_id: if object_id: message_id = tools.generate_tracking_message_id(object_id) else: message_id = make_msgid() msg['Message-Id'] = encode_header(message_id) if references: msg['references'] = encode_header(references) msg['Subject'] = encode_header(subject) msg['From'] = encode_rfc2822_address_header(email_from) del msg['Reply-To'] if reply_to: msg['Reply-To'] = encode_rfc2822_address_header(reply_to) else: msg['Reply-To'] = msg['From'] msg['To'] = encode_rfc2822_address_header(COMMASPACE.join(email_to)) if email_cc: msg['Cc'] = encode_rfc2822_address_header( COMMASPACE.join(email_cc)) if email_bcc: msg['Bcc'] = encode_rfc2822_address_header( COMMASPACE.join(email_bcc)) msg['Date'] = formatdate() # Custom headers may override normal headers or provide additional ones for key, value in headers.iteritems(): msg[ustr(key).encode('utf-8')] = encode_header(value) if subtype == 'html' and not body_alternative and html2text: # Always provide alternative text body ourselves if possible. text_utf8 = tools.html2text( email_body_utf8.decode('utf-8')).encode('utf-8') alternative_part = MIMEMultipart(_subtype="alternative") alternative_part.attach( MIMEText(text_utf8, _charset='utf-8', _subtype='plain')) alternative_part.attach(email_text_part) msg.attach(alternative_part) elif body_alternative: # Include both alternatives, as specified, within a multipart/alternative part alternative_part = MIMEMultipart(_subtype="alternative") body_alternative_utf8 = ustr(body_alternative).encode('utf-8') alternative_body_part = MIMEText(body_alternative_utf8, _subtype=subtype_alternative, _charset='utf-8') alternative_part.attach(alternative_body_part) alternative_part.attach(email_text_part) msg.attach(alternative_part) else: msg.attach(email_text_part) if attachments: for (fname, fcontent) in attachments: filename_rfc2047 = encode_header_param(fname) part = MIMEBase('application', "octet-stream") # The default RFC2231 encoding of Message.add_header() works in Thunderbird but not GMail # so we fix it by using RFC2047 encoding for the filename instead. part.set_param('name', filename_rfc2047) part.add_header('Content-Disposition', 'attachment', filename=filename_rfc2047) part.add_header('Content-ID', '<%s>' % filename_rfc2047) # NEW STUFF part.set_payload(fcontent) Encoders.encode_base64(part) msg.attach(part) return msg
def forge_email(fromaddr, toaddr, subject, content, html_content='', html_images=None, usebcc=False, header=None, footer=None, html_header=None, html_footer=None, ln=CFG_SITE_LANG, charset=None, replytoaddr="", attachments=None): """Prepare email. Add header and footer if needed. @param fromaddr: [string] sender @param toaddr: [string or list-of-strings] list of receivers (if string, then receivers are separated by ',') @param usebcc: [bool] True for using Bcc in place of To @param subject: [string] subject of the email @param content: [string] content of the email @param html_content: [string] html version of the email @param html_images: [dict] dictionary of image id, image path @param header: [string] None for the default header @param footer: [string] None for the default footer @param ln: language @charset: [string] the content charset. By default is None which means to try to encode the email as ascii, then latin1 then utf-8. @param replytoaddr: [string or list-of-strings] to be used for the reply-to header of the email (if string, then receivers are separated by ',') @param attachments: list of paths of files to be attached. Alternatively, every element of the list could be a tuple: (filename, mimetype) @return: forged email as a string""" if html_images is None: html_images = {} content = render_template_to_string('mail_text.tpl', content=content, header=header, footer=footer) if type(toaddr) is not str: toaddr = ','.join(toaddr) if type(replytoaddr) is not str: replytoaddr = ','.join(replytoaddr) toaddr = remove_temporary_emails(toaddr) headers = {} kwargs = {'to': [], 'cc': [], 'bcc': []} if replytoaddr: headers['Reply-To'] = replytoaddr if usebcc: headers['Bcc'] = toaddr kwargs['bcc'] = toaddr.split(',') kwargs['to'] = ['Undisclosed.Recipients:'] else: kwargs['to'] = toaddr.split(',') headers['From'] = fromaddr headers['Date'] = formatdate(localtime=True) headers['User-Agent'] = 'Invenio %s at %s' % (CFG_VERSION, CFG_SITE_URL) if html_content: html_content = render_template_to_string('mail_html.tpl', content=html_content, header=html_header, footer=html_footer) msg_root = EmailMultiAlternatives(subject=subject, body=content, from_email=fromaddr, headers=headers, **kwargs) msg_root.attach_alternative(html_content, "text/html") #if not html_images: # # No image? Attach the HTML to the root # msg_root.attach(msg_text) #else: if html_images: # Image(s)? Attach the HTML and image(s) as children of a # "related" block msg_related = MIMEMultipart('related') #msg_related.attach(msg_text) for image_id, image_path in html_images.iteritems(): attach_embed_image(msg_related, image_id, image_path) msg_root.attach(msg_related) else: msg_root = EmailMessage(subject=subject, body=content, from_email=fromaddr, headers=headers, **kwargs) if attachments: from invenio.bibdocfile import _mimes, guess_format_from_url #old_msg_root = msg_root #msg_root = MIMEMultipart() #msg_root.attach(old_msg_root) for attachment in attachments: try: mime = None if type(attachment) in (list, tuple): attachment, mime = attachment if mime is None: ## Automatic guessing of mimetype mime = _mimes.guess_type(attachment)[0] if mime is None: ext = guess_format_from_url(attachment) mime = _mimes.guess_type("foo" + ext)[0] if not mime: mime = 'application/octet-stream' part = MIMEBase(*mime.split('/', 1)) part.set_payload(open(attachment, 'rb').read()) Encoders.encode_base64(part) part.add_header( 'Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attachment)) msg_root.attach(part) except: register_exception(alert_admin=True, prefix="Can't attach %s" % attachment) return msg_root
def send_mail(config, frm_addr, to_addr, Subject, text, headers=None, files=[], html_body=False, **kw): """ sending a mail using and without using SSL. config is a dictionary that have key, value pairs to connect mail server. We can get config dictionary from UE_config file. frm_addr - (string) id from which we send mails to_addr - (string or list) all the to addresses to send mail kw - In keywords you can give cc and bcc also. headers - It will have all the extra headers to add to mail """ #In headers we send type of data, cc, Subjects if headers is None: headers = {} #with Default settings it works without using SSL and without login. server = config.get('server') port = config.get('port', 25) startSSL = config.get('startSSL', False) startTLS = config.get('startTLS', False) username = config.get('username', None) password = config.get('password', None) cc = kw.get('cc', []) bcc = kw.get('bcc', []) def listify(x): if not isinstance(x, list): return [x] return x #Here are all the recepients. cc = listify(cc) bcc = listify(bcc) to_addr = listify(to_addr) recipients = to_addr + cc + bcc frm_addr = str(frm_addr) files = listify(files) #Here are the headers to send message.. if cc: headers['Cc'] = ", ".join(cc) headers = dictadd( { 'MIME-Version': '1.0', 'Content-Type': 'text/plain; charset=UTF-8', 'Content-Disposition': 'inline', 'From': frm_addr, 'To': ", ".join(to_addr), 'Subject': Subject }, headers) #parsing the to and from addresses import email.Utils from_address = email.Utils.parseaddr(frm_addr)[1] recipients = [email.Utils.parseaddr(r)[1] for r in recipients] #Creating a message to send from server message = MIMEMultipart() for k, v in headers.items(): message.add_header(k, v) if html_body == True: txt_msg = MIMEText(text, 'html', 'UTF-8') else: txt_msg = MIMEText(text, 'plain', 'UTF-8') message.attach(txt_msg) #message.attach(MIMEText(text)) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload(open(f).read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) message.attach(part) #making a connection with server if startSSL: con = smtplib.SMTP_SSL(server, port) else: con = smtplib.SMTP(server) if startTLS: con.starttls() # Logging into server if username and password: con.login(username, password) #Now we are ready to send the data.. con.sendmail(from_address, recipients, message.as_string()) #Closing the connection con.quit()
def start_photobooth(): ################################# Begin Step 1 ################################# print "Get Ready" camera = picamera.PiCamera() camera.resolution = ( 500, 375 ) #use a smaller size to process faster, and tumblr will only take up to 500 pixels wide for animated gifs camera.vflip = True camera.hflip = True camera.saturation = -100 camera.start_preview() i = 1 #iterate the blink of the light in prep, also gives a little time for the camera to warm up while i < prep_delay: GPIO.output(led1_pin, True) sleep(.5) GPIO.output(led1_pin, False) sleep(.5) i += 1 ################################# Begin Step 2 ################################# print "Taking pics" now = time.strftime( "%Y%m%d%H%M%S" ) #get the current date and time for the start of the filename try: #take the photos for i, filename in enumerate( camera.capture_continuous(file_path + now + '-' + '{counter:02d}.jpg')): GPIO.output(led2_pin, True) #turn on the LED print(filename) sleep(0.25) #pause the LED on for just a bit GPIO.output(led2_pin, False) #turn off the LED sleep(capture_delay) # pause in-between shots if i == total_pics - 1: break finally: camera.stop_preview() camera.close() ########################### Begin Step 3 ################################# print "Creating an animated gif" GPIO.output(led3_pin, True) #turn on the LED graphicsmagick = "gm convert -delay " + str( gif_delay ) + " " + file_path + now + "*.jpg " + file_path + now + ".gif" os.system(graphicsmagick) #make the .gif print "Uploading to tumblr. Please check " + tumblr_blog + " soon." connected = is_connected( ) #check to see if you have an internet connection while connected: try: msg = MIMEMultipart() msg['Subject'] = "Photo Booth " + now msg['From'] = addr_from msg['To'] = addr_to file_to_upload = file_path + now + ".gif" print file_to_upload fp = open(file_to_upload, 'rb') part = MIMEBase('image', 'gif') part.set_payload(fp.read()) Encoders.encode_base64(part) part.add_header( 'Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file_to_upload)) fp.close() msg.attach(part) server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(user_name, password) server.sendmail(msg['From'], msg['To'], msg.as_string()) server.quit() break except ValueError: print "Oops. No internect connection. Upload later." try: #make a text file as a note to upload the .gif later file = open(file_path + now + "-FILENOTUPLOADED.txt", 'w') # Trying to create a new file or open one file.close() except: print('Something went wrong. Could not write file.') sys.exit(0) # quit Python GPIO.output(led3_pin, False) #turn off the LED ########################### Begin Step 4 ################################# GPIO.output(led4_pin, True) #turn on the LED try: display_pics(now) except Exception, e: tb = sys.exc_info()[2] traceback.print_exception(e.__class__, e, tb)
def __call__(self): rc = getToolByName(self.context, REFERENCE_CATALOG) workflow = getToolByName(self.context, 'portal_workflow') BatchEmail = self.context.bika_setup.getBatchEmail() username = self.context.portal_membership.getAuthenticatedMember( ).getUserName() self.reporter = self.user_fullname(username) self.reporter_email = self.user_email(username) # signature image self.reporter_signature = "" c = [ x for x in self.bika_setup_catalog(portal_type='LabContact') if x.getObject().getUsername() == username ] if c: sf = c[0].getObject().getSignature() if sf: self.reporter_signature = sf.absolute_url() + "/Signature" # lab address self.laboratory = laboratory = self.context.bika_setup.laboratory self.lab_address = "<br/>".join(laboratory.getPrintAddress()) # group/publish analysis requests by contact ARs_by_contact = {} for ar in self.analysis_requests: contact_uid = ar.getContact().UID() if contact_uid not in ARs_by_contact: ARs_by_contact[contact_uid] = [] ARs_by_contact[contact_uid].append(ar) for contact_uid, ars in ARs_by_contact.items(): ars.sort() self.contact = ars[0].getContact() self.pub_pref = self.contact.getPublicationPreference() batch_size = 'email' in self.pub_pref and BatchEmail or 5 # client address self.client = ars[0].aq_parent self.client_address = "<br/>".join(self.client.getPrintAddress()) self.Footer = self.context.bika_setup.getResultFooter() # send batches of ARs to each contact for b in range(0, len(ars), batch_size): self.batch = ars[b:b + batch_size] self.any_accredited = False self.any_drymatter = False # get all services from all requests in this batch into a # dictionary: # {'Point Of Capture': {'Category': [service,service,...]}} self.services = {} out_fn = "_".join([ar.Title() for ar in self.batch]) for ar in self.batch: if ar.getReportDryMatter(): self.any_drymatter = True states = ("verified", "published") for analysis in ar.getAnalyses(full_objects=True, review_state=states): service = analysis.getService() poc = POINTS_OF_CAPTURE.getValue( service.getPointOfCapture()) cat = service.getCategoryTitle() if poc not in self.services: self.services[poc] = {} if cat not in self.services[poc]: self.services[poc][cat] = [] if service not in self.services[poc][cat]: self.services[poc][cat].append(service) if (service.getAccredited()): self.any_accredited = True # compose and send email if 'email' in self.pub_pref: # render template ar_results = self.ar_results() ar_results = safe_unicode(ar_results).encode('utf-8') debug_mode = App.config.getConfiguration().debug_mode if debug_mode: open( join(Globals.INSTANCE_HOME, 'var', out_fn + ".html"), "w").write(ar_results) ramdisk = StringIO() pdf = createPdf(ar_results, ramdisk) pdf_data = ramdisk.getvalue() ramdisk.close() if debug_mode: open( join(Globals.INSTANCE_HOME, 'var', out_fn + ".pdf"), "wb").write(pdf_data) mime_msg = MIMEMultipart('related') mime_msg['Subject'] = self.get_mail_subject() mime_msg['From'] = formataddr( (encode_header(laboratory.getName()), laboratory.getEmailAddress())) mime_msg['To'] = formataddr( (encode_header(self.contact.getFullname()), self.contact.getEmailAddress())) mime_msg.preamble = 'This is a multi-part MIME message.' msg_txt = MIMEText(ar_results, _subtype='html') mime_msg.attach(msg_txt) if not pdf.err: part = MIMEBase('application', "application/pdf") part.add_header( 'Content-Disposition', 'attachment; filename="%s.pdf"' % out_fn) part.set_payload(pdf_data) Encoders.encode_base64(part) mime_msg.attach(part) try: host = getToolByName(self.context, 'MailHost') host.send(mime_msg.as_string(), immediate=True) except SMTPServerDisconnected, msg: if not debug_mode: raise SMTPServerDisconnected(msg) except SMTPRecipientsRefused, msg: raise WorkflowException(str(msg)) if self.action == 'publish': for ar in self.batch: try: workflow.doActionFor(ar, 'publish') except WorkflowException: pass ## if not pdf.err: ## setheader = self.request.RESPONSE.setHeader ## setheader('Content-Type', 'application/pdf') ## setheader("Content-Disposition", "attachment;filename=\"%s.pdf\"" % out_fn) ## self.request.RESPONSE.write(pdf_data) else: raise Exception, "XXX pub_pref %s" % self.pub_pref
def get_mail_text(self, fields, request, context): """Get header and body of e-mail as text (string) """ headerinfo = self.get_header_info(fields, request, context) body = self.get_mail_body(fields, request, context) if not isinstance(body, unicode): body = unicode(body, 'UTF-8') email_charset = 'utf-8' # always use text/plain for encrypted bodies subtype = getattr( self, 'gpg_keyid', False) and 'plain' or self.body_type or 'html' mime_text = MIMEText(body.encode(email_charset, 'replace'), _subtype=subtype, _charset=email_charset) attachments = self.get_attachments(fields, request) if attachments: outer = MIMEMultipart() outer.attach(mime_text) else: outer = mime_text # write header for key, value in headerinfo.items(): outer[key] = value # write additional header additional_headers = self.additional_headers or [] for a in additional_headers: key, value = a.split(':', 1) outer.add_header(key, value.strip()) for attachment in attachments: filename = attachment[0] ctype = attachment[1] # encoding = attachment[2] content = attachment[3] if ctype is None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': msg = MIMEText(content, _subtype=subtype) elif maintype == 'image': msg = MIMEImage(content, _subtype=subtype) elif maintype == 'audio': msg = MIMEAudio(content, _subtype=subtype) else: msg = MIMEBase(maintype, subtype) msg.set_payload(content) # Encode the payload using Base64 Encoders.encode_base64(msg) # Set the filename parameter msg.add_header( 'Content-Disposition', 'attachment', filename=filename) outer.attach(msg) return outer.as_string()
def add_attachment(self, filepath): attachment = MIMEBase('application', 'octet-stream') attachment.set_payload(open(filepath, 'rb').read()) Encoders.encode_base64(attachment) attachment.add_header('Content-Disposition', 'attachment; filename="{filename}"'.format(filename=os.path.basename(filepath))) self.attachments.append(attachment)