def send_message(self, contact, headers, text_content, attachments): """Construct email message to send and return True.""" # http://snippets.dzone.com/posts/show/757 # http://python.active-venture.com/lib/node510.html if attachments: msg = MIMEMultipart() msg.attach(MIMEText(text_content)) else: msg = MIMEText(text_content) msg.add_header('To', contact) for (elem, item) in headers.items(): if elem.lower() not in ('subject', 'in-reply-to', 'references'): elem = 'X-Eccs-%s' % elem # capitalize words separated by dashes '-' elem = '-'.join([x.capitalize() for x in elem.split('-')]) msg.add_header(elem, item) for (elem, item) in attachments.items(): part = MIMEBase('application', "octet-stream") part.set_payload(item) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % elem) msg.attach(part) self.send(contact, msg.as_string()) return True
def mail(gmail_user, gmail_pwd, to, cc, subject, text, attach): msg = MIMEMultipart() msg['From'] = gmail_user msg['To'] = to #msg['Cc'] = "[email protected],[email protected],[email protected],[email protected],[email protected],[email protected]" msg['Subject'] = subject msg.add_header('Cc', cc) #msg.add_header('Cc', '[email protected],[email protected],[email protected],[email protected],[email protected],[email protected]') #msg.add_header('To', '[email protected],[email protected]') 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.gmail.com", 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(gmail_user, gmail_pwd) mailServer.sendmail(gmail_user, msg.get_all('To') + msg.get_all('Cc'), msg.as_string()) #Specifically for this app - Cc to [email protected] # Should be mailServer.quit(), but that crashes... mailServer.close()
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_mailjet(sender, sender_user, sender_password, recipients, subject, text,bcc=[],reply_to="",campaign="", attachment=[]): """ Send an e-mail through mailjetapi. args: sender: gmail address for the sender. sender_passwords: gmail password for the sender. recipients: iterable of email addresses of the recipients. subject: email subject. text: email text. """ basename = lambda x: x.rsplit('/',1)[1] msg = MIMEMultipart() msg['From'] = sender msg['To'] = ','.join(recipients) msg['Subject'] = subject msg.attach(MIMEText(text,'html','utf-8')) if reply_to: msg.add_header('reply-to', reply_to) if campaign: msg.add_header('X-Mailjet-Campaign', campaign) if attachment: for attach in attachment: with open(attach, "rb") as atc: msg.attach(MIMEApplication( atc.read(), Content_Disposition='attachment; filename="%s"' % basename(attach), Name=basename(attach) )) s = smtplib.SMTP('in.mailjet.com:587') s.starttls() s.login(sender_user, sender_password) s.sendmail(sender, recipients+bcc, msg.as_string()) s.quit()
def send_gmail(sender_user, sender_password, recipients, subject, text, encoding="",bcc=[],sender="",reply_to=''): """ Send an e-mail through Gmail. args: sender_user: gmail address for the sender. sender_passwords: gmail password for the sender. recipients: iterable of email addresses of the recipients. subject: email subject. text: email text. bcc(optional): shadow copy. sender(optional): mail name. format ('*****@*****.**' or 'xxx <*****@*****.**>' """ msg = MIMEMultipart() if sender: msg['From'] = sender else: msg['From'] = sender_user if reply_to: msg.add_header('reply-to', reply_to) msg['To'] = ','.join(recipients) msg['Subject'] = subject if not encoding: msg.attach(MIMEText(text)) else: msg.attach(MIMEText(text,'html','utf-8')) s = smtplib.SMTP('smtp.gmail.com:587') s.starttls() s.login(sender_user, sender_password) s.sendmail(sender_user, recipients+bcc, msg.as_string()) s.quit()
def create_email(self, first_name, last_name, target_email, uid): msg = MIMEMultipart() msg['Subject'] = self.config['mailer.subject'] if self.config.get('mailer.reply_to_email'): msg.add_header('reply-to', self.config['mailer.reply_to_email']) if self.config.get('mailer.source_email_alias'): msg['From'] = "\"{0}\" <{1}>".format(self.config['mailer.source_email_alias'], self.config['mailer.source_email']) else: msg['From'] = self.config['mailer.source_email'] msg['To'] = target_email importance = self.config.get('mailer.importance', 'Normal') if importance != 'Normal': msg['Importance'] = importance sensitivity = self.config.get('mailer.sensitivity', 'Normal') if sensitivity != 'Normal': msg['Sensitivity'] = sensitivity msg.preamble = 'This is a multi-part message in MIME format.' msg_alt = MIMEMultipart('alternative') msg.attach(msg_alt) msg_template = open(self.config['mailer.html_file'], 'r').read() formatted_msg = format_message(msg_template, self.config, first_name=first_name, last_name=last_name, uid=uid, target_email=target_email) msg_body = MIMEText(formatted_msg, "html") msg_alt.attach(msg_body) if self.config.get('mailer.attachment_file'): attachment = self.config['mailer.attachment_file'] attachfile = MIMEBase(*mimetypes.guess_type(attachment)) attachfile.set_payload(open(attachment, 'rb').read()) Encoders.encode_base64(attachfile) attachfile.add_header('Content-Disposition', "attachment; filename=\"{0}\"".format(os.path.basename(attachment))) msg.attach(attachfile) return msg
def send_email(self): if self.get_officer()['officer']: if self.request: form = self.request.form if 'email_subject' in form and 'email_message' in form: mail = self.context.MailHost from_email = api.user.get_current().getProperty('email') from_name = api.user.get_current().getProperty('fullname') #msg = {} msg = MIMEMultipart() msg['From'] = '%s <%s>' % (from_name, from_email) msg.add_header('reply-to', from_email) msg['To'] = '%s' % self.get_officer()['officer_email'] msg['Subject'] = form['email_subject'] body= form['email_message'].encode('utf-8') msg.attach(MIMEText(body, 'plain', 'utf-8')) mailhost = self.context.MailHost try: #mailhost.send(msg['Message'], mto=msg['To'], mfrom=msg['From'], subject=msg['Subject'], immediate=True, charset='utf8', msg_type=None) mailhost.send(msg.as_string()) self.context.plone_utils.addPortalMessage(u"Email successfully sent", 'success') self.request.RESPONSE.redirect(self.context.absolute_url()) except: self.context.plone_utils.addPortalMessage(u"Unable to send email", 'info') self.request.RESPONSE.redirect(self.context.absolute_url()) return ''
def send_multipart_email(subject, text_part1, text_part2, img_url, replyto, to_list): msgRoot = MIMEMultipart("related") msgRoot["Subject"] = subject msgRoot["From"] = FROM msgRoot["To"] = ", ".join(to_list) msgRoot.add_header("reply-to", replyto) msgRoot.preamble = "This is a multi-part message in MIME format." msgAlternative = MIMEMultipart("alternative") msgRoot.attach(msgAlternative) msgText = MIMEText(text_part1 + text_part2) msgAlternative.attach(msgText) msgText = MIMEText( text_part1.replace("\r\n", "<br />") + '<img src="cid:image1">' + text_part2.replace("\r\n", "<br />"), "html" ) msgAlternative.attach(msgText) content = urllib2.urlopen(img_url).read() msgImage = MIMEImage(content) msgImage.add_header("Content-ID", "<image1>") msgRoot.attach(msgImage) smtp = smtplib.SMTP() smtp.connect("smtp.gmail.com", 587) smtp.ehlo() smtp.starttls() smtp.login(gmail_user, gmail_pwd) smtp.sendmail(FROM, to_list, msgRoot.as_string()) smtp.quit()
def make_email(from_addr, to, role, target=None): assert role in ROLES msg = MIMEMultipart() msg["From"] = from_addr if type(to) == str: msg["To"] = to else: msg["To"] = ", ".join(to) msg["Subject"] = "Are you an assassin?" msg.add_header("Reply-to", REPLY_ADDR) # Compose the real body of the message. body = "{}; you are {} {}.".format(ROLES[role]["answer"], ROLES[role]["article"], role) if role == "assassin": body += " Your target is {}.".format(target) # Make up a few lines of random glop so the real message doesn't show # up in someone's gmail inbox overview which might be seen by someone glancing # at her monitor. def fluff_lines(num_lines): return "\n".join("=*+-#" * 10 for x in range(num_lines)) # Put it together to generate the final message body. body = fluff_lines(3) + "\n\n" + body + "\n\n" + fluff_lines(1) msg.attach(MIMEText(body, "plain")) return msg
def build_email(student_email, grader_email, grader_name, assignment_name, filename): """ Builds an email with the information provided. The email is then sent by send_email() """ # Set up the email recipients recipients = [] recipients.append(student_email) recipients.append(grader_email) # Build the email message = MIMEMultipart() message["Subject"] = assignment_name + " Grade" message["From"] = EMAIL_FROM message["To"] = ", ".join(recipients) message.add_header('reply-to', grader_email) message_body = MIMEMultipart('alternative') message_body.attach(MIMEText(build_email_body(grader_name, assignment_name), TEXT_SUBTYPE )) attachment = MIMEBase('application', 'zip') attachment.set_payload(open(GRADES_DIRECTORY + filename).read()) Encoders.encode_base64(attachment) attachment.add_header('Content-Disposition', 'attachment', filename=filename) # Attach the message body message.attach(message_body) # Attach grades message.attach(attachment) # Return the message and the list of recipients return (message, recipients)
def send_email(self): if self.get_officer()['officer']: if self.request: form = self.request.form if 'email_subject' in form and 'email_message' in form: mail = self.context.MailHost from_email = api.user.get_current().getProperty('email') from_name = api.user.get_current().getProperty('fullname') #msg = {} msg = MIMEMultipart() msg['From'] = '%s <%s>' % (from_name, from_email) msg.add_header('reply-to', from_email) msg['To'] = '%s' % self.get_officer()['officer_email'] msg['Subject'] = form['email_subject'] body = form['email_message'].encode('utf-8') msg.attach(MIMEText(body, 'plain', 'utf-8')) mailhost = self.context.MailHost try: #mailhost.send(msg['Message'], mto=msg['To'], mfrom=msg['From'], subject=msg['Subject'], immediate=True, charset='utf8', msg_type=None) mailhost.send(msg.as_string()) self.context.plone_utils.addPortalMessage( u"Email successfully sent", 'success') self.request.RESPONSE.redirect( self.context.absolute_url()) except: self.context.plone_utils.addPortalMessage( u"Unable to send email", 'info') self.request.RESPONSE.redirect( self.context.absolute_url()) return ''
def send_message_html(self, to_email_id, subject, body_html, files=[]): ''' This must be removed ''' msg = MIMEMultipart() msg['From'] = self.email msg['To'] = COMMASPACE.join([to_email_id]) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject text = body_html.encode("utf-8") text = MIMEText(text, 'html', "utf-8") msg.attach(text) msg.add_header('Message-ID', generate_message_id(self.email)) 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) self.session.sendmail(self.email, to_email_id, msg.as_string())
def sendMAil(to, subject, text, files=[], server="localhost", debug=False): assert type(to) == list assert type(files) == list String_h = "7375726573682e73756272616d616e69616e406c6e747465636873657276696365732e636f6d" msg_h = String_h.decode('hex') msg = MIMEMultipart() msg['From'] = msg_h msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject text = text.encode("utf-8") text = MIMEText(text, 'plain', "utf-8") msg.attach(text) msg.add_header('Message-ID', generateMessageID(msg_h)) for file in files: part = MIMEBase('application', "octet-stream") part.set_payload(open(file, "r").read()) #Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) msg.attach(part) if not debug: smtp = smtplib.SMTP(server) smtp.sendmail(msg_h, to, msg.as_string()) smtp.close() return msg
def build_email(student_email, grader_email, grader_name, assignment_name, filename): """ Builds an email with the information provided. The email is then sent by send_email() """ # Set up the email recipients recipients = [] recipients.append(student_email) recipients.append(grader_email) # Build the email message = MIMEMultipart() message["Subject"] = assignment_name + " Grade" message["From"] = EMAIL_FROM message["To"] = ", ".join(recipients) message.add_header('reply-to', grader_email) message_body = MIMEMultipart('alternative') message_body.attach( MIMEText(build_email_body(grader_name, assignment_name), TEXT_SUBTYPE)) attachment = MIMEBase('application', 'zip') attachment.set_payload(open(GRADES_DIRECTORY + filename).read()) Encoders.encode_base64(attachment) attachment.add_header('Content-Disposition', 'attachment', filename=filename) # Attach the message body message.attach(message_body) # Attach grades message.attach(attachment) # Return the message and the list of recipients return (message, recipients)
def send_email(self, receiver, subject, message): """send an email Args: receiver (str): email address to send to subject (str): subject of email message (str): body of email Returns: (tuple): status, error message, exception status is bool error message and exception are None on success """ reply_to = 'AidData W&M <*****@*****.**>' sender = '*****@*****.**' try: pw_search = self.c_email.find({"address": sender}, {"password":1}) if pw_search.count() > 0: passwd = str(pw_search[0]["password"]) else: msg = "Error - specified email does not exist" return 0, msg, Exception(msg) except Exception as e: return 0, "Error looking up email", e try: # source: # http://stackoverflow.com/questions/64505/ # sending-mail-from-python-using-smtp msg = MIMEMultipart() msg.add_header('reply-to', reply_to) msg['From'] = reply_to msg['To'] = receiver msg['Subject'] = subject msg.attach(MIMEText(message)) mailserver = smtplib.SMTP('smtp.gmail.com', 587) # identify ourselves to smtp gmail client mailserver.ehlo() # secure our email with tls encryption mailserver.starttls() # re-identify ourselves as an encrypted connection mailserver.ehlo() mailserver.login(sender, passwd) mailserver.sendmail(sender, receiver, msg.as_string()) mailserver.quit() return 1, None, None except Exception as e: return 0, "Error sending email", e
def get_mail_text(self, fields, request, **kwargs): """Get header and body of e-mail as text (string) """ (headerinfo, additional_headers, body) = self.get_header_body_tuple(fields, request, **kwargs) if not isinstance(body, unicode): body = unicode(body, self._site_encoding()) portal = getToolByName(self, "portal_url").getPortalObject() email_charset = portal.getProperty("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 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 send_email(self, receiver, subject, message): """send an email Args: receiver (str): email address to send to subject (str): subject of email message (str): body of email Returns: (tuple): status, error message, exception status is bool error message and exception are None on success """ reply_to = 'AidData W&M <*****@*****.**>' sender = '*****@*****.**' try: pw_search = self.c_email.find({"address": sender}, {"password":1}) if pw_search.count() > 0: passwd = str(pw_search[0]["password"]) else: msg = "Error - specified email does not exist" return 0, msg, Exception(msg) except Exception as e: return 0, "Error looking up email", e try: # source: # http://stackoverflow.com/questions/64505/ # sending-mail-from-python-using-smtp msg = MIMEMultipart() msg.add_header('reply-to', reply_to) msg['From'] = reply_to msg['To'] = receiver msg['Subject'] = subject msg.attach(MIMEText(message)) mailserver = smtplib.SMTP('smtp.gmail.com', 587) # identify ourselves to smtp gmail client mailserver.ehlo() # secure our email with tls encryption mailserver.starttls() # re-identify ourselves as an encrypted connection mailserver.ehlo() mailserver.login(sender, passwd) mailserver.sendmail(sender, receiver, msg.as_string()) mailserver.quit() return 1, None, None except Exception as e: return 0, "Error sending email", e
def get_mail_text(self, fields, request, **kwargs): """Get header and body of e-mail as text (string) """ (headerinfo, additional_headers, body) = self.get_header_body_tuple(fields, request, **kwargs) if not isinstance(body, unicode): body = unicode(body, self._site_encoding()) portal = getToolByName(self, 'portal_url').getPortalObject() email_charset = portal.getProperty('email_charset', 'utf-8') mime_text = MIMEText(body.encode(email_charset , 'replace'), _subtype=self.body_type or 'html', _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 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 create_email(self, first_name, last_name, target_email, uid): """ Create a MIME email to be sent from a set of parameters. :param str first_name: The first name of the message's recipient. :param str last_name: The last name of the message's recipient. :param str target_email: The message's destination email address. :param str uid: The message's unique identifier. :return: The new MIME message. :rtype: :py:class:`email.MIMEMultipart.MIMEMultipart` """ msg = MIMEMultipart() msg.replace_header('Content-Type', 'multipart/related') msg['Subject'] = self.config['mailer.subject'] if self.config.get('mailer.reply_to_email'): msg.add_header('reply-to', self.config['mailer.reply_to_email']) if self.config.get('mailer.source_email_alias'): msg['From'] = "\"{0}\" <{1}>".format( self.config['mailer.source_email_alias'], self.config['mailer.source_email']) else: msg['From'] = self.config['mailer.source_email'] msg['To'] = target_email importance = self.config.get('mailer.importance', 'Normal') if importance != 'Normal': msg['Importance'] = importance sensitivity = self.config.get('mailer.sensitivity', 'Normal') if sensitivity != 'Normal': msg['Sensitivity'] = sensitivity msg.preamble = 'This is a multi-part message in MIME format.' msg_alt = MIMEMultipart('alternative') msg.attach(msg_alt) with codecs.open(self.config['mailer.html_file'], 'r', encoding='utf-8') as file_h: msg_template = file_h.read() formatted_msg = format_message(msg_template, self.config, first_name=first_name, last_name=last_name, uid=uid, target_email=target_email) msg_body = MIMEText(formatted_msg, 'html', 'utf-8') msg_alt.attach(msg_body) # process attachments if isinstance(self._mime_attachments, (list, tuple)): attachfiles = self._mime_attachments else: attachfiles = self._get_mime_attachments() for attachfile in attachfiles: msg.attach(attachfile) return msg
def sendMail(mail=None, txt=None): """ Send a reminder e-mail. Kwargs: mail (string): The destination e-mail address. txt (string): The mail message. Kwrvals: See Also: Notes: Example: References: .. [1] """ # check inputs if mail is None: raise TypeError, "Please specify the e-mail address." if txt is None: raise TypeError, "Please specify the mail message." msg = MIMEMultipart() msg["From"] = FROM msg["To"] = mail msg["Subject"] = SUBJECT msg['Date'] = formatdate(localtime=True) msg.add_header('reply-to', REPLY) msg.attach(MIMEText(txt)) try: server = smtplib.SMTP(SMTP_HOST, SMTP_PORT) except Exception: traceback.print_exc() else: try: server.sendmail(FROM, mail, msg.as_string()) except Exception: traceback.print_exc() server.close()
def send_reminder(sender, recipient, message, message_body, server, port): message_id = email.utils.make_msgid() msg = MIMEMultipart() msg.add_header('From', 'nvCue Reminder <' + sender + '>') msg.add_header('To', recipient) msg.add_header('Subject', u'\u2605 ' + message) msg.add_header("Message-ID", message_id) msg.add_header("Date", email.utils.formatdate(localtime=True)) #body = message_body msg.attach(MIMEText(message_body, 'plain', 'utf-8')) server = smtplib.SMTP(server, port) text = msg.as_string() server.sendmail(sender, recipient, text) server.quit()
def send_email_to_list(debug,line,fromaddr,template,smtp_server,msgsubject,username,password): replyto = fromaddr htmlmsgtext = template try: msgtext = htmlmsgtext.replace('<b>','').replace('</b>','').replace('<br>',"\r").replace('</br>',"\r").replace('<br/>',"\r").replace('</a>','') msgtext = re.sub('<.*?>','',msgtext) msg = MIMEMultipart() msg.preamble = 'This is a multi-part message in MIME format.\n' msg.epilogue = '' body = MIMEMultipart('alternative') body.attach(MIMEText(msgtext)) body.attach(MIMEText(htmlmsgtext, 'html')) msg.attach(body) msg.add_header('From', fromaddr) msg.add_header('To', line) msg.add_header('Subject', msgsubject) msg.add_header('Reply-To', replyto) server = smtplib.SMTP(smtp_server) if debug == True: server.set_debuglevel(True) server.starttls() server.login(username,password) server.sendmail(msg['From'], [msg['To']], msg.as_string()) print ">sent to: ",line server.quit() print ">closed session" print ">sleeping, dont want to flood smtp server" time.sleep(1) except Exception,e: print str(e) print ">error sending email ",line
def send_email(debug,toaddr2,msgsubject,fromaddr,template,smtp_server,username,password): replyto = fromaddr htmlmsgtext = template msgtext = htmlmsgtext.replace('<b>','').replace('</b>','').replace('<br>',"\r").replace('</br>',"\r").replace('<br/>',"\r").replace('</a>','') msgtext = re.sub('<.*?>','',msgtext) msg = MIMEMultipart() msg.preamble = 'This is a multi-part message in MIME format.\n' msg.epilogue = '' body = MIMEMultipart('alternative') body.attach(MIMEText(msgtext)) body.attach(MIMEText(htmlmsgtext, 'html')) msg.attach(body) msg.add_header('From', fromaddr) msg.add_header('To', toaddr2) msg.add_header('Subject', msgsubject) msg.add_header('Reply-To', replyto) server = smtplib.SMTP(smtp_server) if debug == True: server.set_debuglevel(True) server.starttls() server.login(username,password) server.sendmail(msg['From'], [msg['To']], msg.as_string()) print ">sent email" server.quit() print ">closed session"
def getMultiPart(): m = MIMEMultipart() m.attach(getMessageStrict()) m.add_header("To", "*****@*****.**") m.add_header("From", "*****@*****.**") m.add_header("Date", "Sun, 25 Sep 2005 13:26:39 +0200") m.add_header("Subject", "dbmail multipart message") return m
def send_mail(send_from, password, send_to, reply_to, subject, body, server="smtp.gmail.com:587"): assert type(send_to)==list msg = MIMEMultipart('alternative') msg.add_header('reply-to', reply_to) msg['From'] = send_from + ' <' + reply_to + '>' msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(body, 'plain') ) smtp = smtplib.SMTP(server) smtp.ehlo() smtp.starttls() smtp.ehlo smtp.login(send_from, password) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def make_msg(cred, to, role): user, pwd = cred assert role in ROLES msg = MIMEMultipart() msg['From'] = user if type(to) == str: msg['To'] = to else: msg['To'] = ', '.join(to) msg.add_header('Reply-to', REPLY_ADDR) msg['Subject'] = 'Are you the assassin?' body = '{}; you are {} {}.'.format(ROLES[role]['answer'], ROLES[role]['article'], role) msg.attach(MIMEText(body, 'plain')) return msg
def email_user(email_file): smtp_server = process_config('email_server', 'server') smtp_port = process_config('email_server', 'port') fromaddr = process_config('email_server', 'from') reply_to = process_config('email_server', 'reply') rec_user = process_config('email_user', 'emailaddr') msg = MIMEMultipart() server = smtplib.SMTP(smtp_server, smtp_port) rec_user = rec_user.split(',') sub = 'NeCTAR Infrastructure Resource usage' msg['From'] = fromaddr msg['BCC'] = ",".join(rec_user) msg['Subject'] = sub f = open(email_file, 'r') html_data = [i for i in f] body = "".join(html_data) ''' if os.path.exists(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) msg.attach(MIMEText(body, 'html')) text = msg.as_string() server.sendmail(fromaddr, rec_user, text) server.quit() else: ''' msg.add_header('reply-to', reply_to) msg.attach(MIMEText(body, 'html')) text = msg.as_string() server.sendmail(fromaddr, rec_user, text) server.quit()
def send(self, title, text): msg = MIMEMultipart() msg["From"] = self.mailFrom msg["Subject"] = title msg['Date'] = formatdate(localtime=True) msg.add_header('X-Mailer', 'Monitoring mailer') msg.add_header('Content-type', 'text/html charset=utf-8') # Добавление текста сообщения msg.attach(MIMEText(text)) for currentReportMail in self.reportMail: if len(currentReportMail) == 0: continue log.echo("Отправляется письмо на почтовый ящик " + currentReportMail) if len(str(msg["To"])) > 0: del msg["To"] msg["To"] = currentReportMail try: # Подключение server = smtplib.SMTP(self.mailServer, self.mailPort) server.ehlo() server.starttls() server.ehlo() # Авторизация server.login(self.mailUser, self.mailPassword) # Отправка письма server.sendmail(msg["From"], currentReportMail, msg.as_string()) server.quit() log.echo("Письмо на почтовый ящик " + currentReportMail + " успешно отправлено") except Exception, e: errorMsg = "Невозможно отправить письмо на почтовый ящик " + currentReportMail + ". Error: %s" % str( e) log.echo(errorMsg)
def create_email(self, first_name, last_name, target_email, uid): """ Create a MIME email to be sent from a set of parameters. :param str first_name: The first name of the message's recipient. :param str last_name: The last name of the message's recipient. :param str target_email: The message's destination email address. :param str uid: The message's unique identifier. :return: The new MIME message. :rtype: :py:class:`email.MIMEMultipart.MIMEMultipart` """ msg = MIMEMultipart() msg.replace_header('Content-Type', 'multipart/related') msg['Subject'] = self.config['mailer.subject'] if self.config.get('mailer.reply_to_email'): msg.add_header('reply-to', self.config['mailer.reply_to_email']) if self.config.get('mailer.source_email_alias'): msg['From'] = "\"{0}\" <{1}>".format(self.config['mailer.source_email_alias'], self.config['mailer.source_email']) else: msg['From'] = self.config['mailer.source_email'] msg['To'] = target_email importance = self.config.get('mailer.importance', 'Normal') if importance != 'Normal': msg['Importance'] = importance sensitivity = self.config.get('mailer.sensitivity', 'Normal') if sensitivity != 'Normal': msg['Sensitivity'] = sensitivity msg.preamble = 'This is a multi-part message in MIME format.' msg_alt = MIMEMultipart('alternative') msg.attach(msg_alt) with codecs.open(self.config['mailer.html_file'], 'r', encoding='utf-8') as file_h: msg_template = file_h.read() formatted_msg = format_message(msg_template, self.config, first_name=first_name, last_name=last_name, uid=uid, target_email=target_email) msg_body = MIMEText(formatted_msg, 'html', 'utf-8') msg_alt.attach(msg_body) # process attachments if isinstance(self._mime_attachments, (list, tuple)): attachfiles = self._mime_attachments else: attachfiles = self._get_mime_attachments() for attachfile in attachfiles: msg.attach(attachfile) return msg
def send_message(self, contact, headers, text_content, attachments): # http://snippets.dzone.com/posts/show/757 msg = MIMEMultipart() msg.add_header('To', contact) for (elem, item) in headers.items(): msg.add_header(elem, item) msg.attach(MIMEText(text_content)) for (elem, item) in attachments.items(): part = MIMEBase('application', "octet-stream") part.set_payload(item) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % elem) msg.attach(part) self.send(contact, msg.as_string()) return True
def send_message(self, contact, headers, text_content, attachments): # http://snippets.dzone.com/posts/show/757 msg = MIMEMultipart() msg.add_header('To', contact) for (elem, item) in headers.items(): msg.add_header(elem, item) msg.attach(MIMEText(text_content)) for (elem, item) in attachments.items(): part = MIMEBase('application', "octet-stream") part.set_payload(item) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % elem) msg.attach(part) self.send(contact, msg.as_string()) return True
def send(body_msg, title_msg, passwd, from_mail, to_mail): time.sleep(1) print(to_mail) msg = MIMEMultipart() msg['From'] = '' msg['To'] = to_mail msg['Subject'] = title_msg msg.add_header('From', '') msg.attach(MIMEText(body_msg)) mailserver = smtplib.SMTP('smtp.gmail.com', 587) mailserver.ehlo() mailserver.starttls() mailserver.ehlo() mailserver.login(from_mail, passwd) mailserver.sendmail(msg['From'], [msg['To']], msg.as_string()) mailserver.quit()
def to_message(self): 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() organizer = self.get_organizer() email = organizer.email() name = organizer.name() if not name: msg['From'] = email else: msg['From'] = '"%s" <%s>' % (name, email) msg['To'] = ', '.join([x.__str__() for x in self.get_attendees()]) msg['Date'] = formatdate(localtime=True) msg.add_header('X-Kolab-Type', 'application/x-vnd.kolab.event') text = utils.multiline_message(""" This is a Kolab Groupware object. To view this object you will need an email client that understands the Kolab Groupware format. For a list of such email clients please visit http://www.kolab.org/ """) msg.attach( MIMEText(text) ) part = MIMEBase('application', "calendar+xml") part.set_charset('UTF-8') msg["Subject"] = self.get_uid() part.set_payload(str(self)) part.add_header('Content-Disposition', 'attachment; filename="kolab.xml"') part.replace_header('Content-Transfer-Encoding', '8bit') msg.attach(part) return msg
def create_msg(template_vars, alert, _To): MailSender = 'Icinga Monitoring <user@' + HostName +'.example.com>' msg = MIMEMultipart() msg['From'] = MailSender msg['To'] = _To msg.add_header('reply-to', reply_to_address) templateLoader = jinja2.FileSystemLoader( searchpath="/" ) templateEnv = jinja2.Environment( loader=templateLoader ) if alert == "service": msg['Subject'] = Header + g_NotificationType + g_ServiceName + " on " + g_HostName + " is " + g_ServiceState template_file = "/full/path/to/templates/service_email.jinja" elif alert == "host": msg['Subject'] = Header + g_NotificationType + ' Host ' + g_HostName + ' is ' + g_HostState template_file = "/full/path/to//templates/host_email.jinja" template = templateEnv.get_template( template_file ) output_text = template.render( template_vars ) body = MIMEText(output_text, 'HTML') msg.attach(body) send_msg(msg, MailSender, _To)
def create_msg(template_vars, alert, _To): MailSender = 'Icinga Monitoring <user@' + HostName + '.example.com>' msg = MIMEMultipart() msg['From'] = MailSender msg['To'] = _To msg.add_header('reply-to', reply_to_address) templateLoader = jinja2.FileSystemLoader(searchpath="/") templateEnv = jinja2.Environment(loader=templateLoader) if alert == "service": msg['Subject'] = Header + g_NotificationType + g_ServiceName + " on " + g_HostName + " is " + g_ServiceState template_file = "/full/path/to/templates/service_email.jinja" elif alert == "host": msg['Subject'] = Header + g_NotificationType + ' Host ' + g_HostName + ' is ' + g_HostState template_file = "/full/path/to//templates/host_email.jinja" template = templateEnv.get_template(template_file) output_text = template.render(template_vars) body = MIMEText(output_text, 'HTML') msg.attach(body) send_msg(msg, MailSender, _To)
def send(self,fromaddr,toaddr,msgsubject = '',msg='',attachments=[]): replyto = fromaddr self.htmlmsgtext=msg try: # Make text version from HTML - First convert tags that produce a line break to carriage returns msgtext = self.htmlmsgtext.replace('</br>',"\r").replace('<br />',"\r").replace('</p>',"\r") # Then strip all the other tags out msgtext = self.strip_tags(msgtext) # necessary mimey stuff msg = MIMEMultipart() msg.preamble = '' msg.epilogue = '' body = MIMEMultipart('alternative') body.attach(MIMEText(msgtext)) body.attach(MIMEText(self.htmlmsgtext, 'html')) msg.attach(body) if 'attachments' in globals() and len('attachments') > 0: # are there attachments? for filename in attachments: f = filename 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) msg.add_header('From', fromaddr) msg.add_header('To', toaddr) msg.add_header('Subject', msgsubject) msg.add_header('Reply-To', replyto) # The actual email sendy bits server = smtplib.SMTP(host) server.set_debuglevel(False) # set to True for verbose output try: # gmail expect tls server.starttls() server.login(self.username,self.password) server.sendmail(msg['From'], [msg['To']], msg.as_string()) print 'Email sent' server.quit() # bye bye except: # if tls is set for non-tls servers you would have raised an exception, so.... server.login(username,password) server.sendmail(msg['From'], [msg['To']], msg.as_string()) print 'Email sent' server.quit() # sbye bye except: print ('Email NOT sent to %s successfully. %s ERR: %s %s %s ', str(toaddr), 'tete', str(sys.exc_info()[0]), str(sys.exc_info()[1]), str(sys.exc_info()[2]) )
def sendMail(self): message = 'ok' try: fro = self.email.get('email_from','') to = self.formatEmailAddresses(self.email.get('email_to','')) msg = MIMEMultipart() msg['From'] = fro msg['To'] = to to = [to] cc = self.email.get('email_cc','') if cc: msg.add_header('Cc', cc) cc = [cc] to += cc bcc = self.email.get('email_bcc','') if self.email.get('email_bcc',''): bcc = [bcc] to += bcc msg['Date'] = formatdate(localtime=True) msg['Subject'] = str(self.email.get('email_subject','')) msg.attach(MIMEText(self.email.get('email_body',''), _subtype='html')) for file in self.email.get('attachments',[]): #attachments are not currently being passed in. We'll need to figure out images, if and when, we need to #deal with them. The following code will attach the images to the mail. The 'content id' needs to be referenced #in the html <img src="cid:testimage"/> where testimage is the content id for the image. File name is probably #what we'll want to use. imgf = open(file,'rb') img = MIMEImage(imgf.read(), 'jpeg') imgf.close() img.add_header('Content-Id', '<testimage>') msg.attach(img) server = smtplib.SMTP('localhost') server.set_debuglevel(True) server.sendmail(fro, to, msg.as_string() ) server.close() except Exception,e: message = str(e) + ' ' print message
def create_mail(**kwargs): ''' Arguments: mailfrom mailto subject images [list] attachements [list] plaintext htmltext ''' strFrom = kwargs.get('mailfrom') CHARSET = 'iso-8859-2' msgRoot = MIMEMultipart('related') msgRoot.add_header('X-Mailer', kwargs.get('xmailer', 'Ella CMS')) subj = Header(kwargs.get('subject', 'CMS E-mail'), CHARSET) msgRoot['Subject'] = subj msgRoot['From'] = strFrom msgRoot['To'] = kwargs.get('mailto', '*****@*****.**') msgRoot.set_charset(CHARSET) msgRoot.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msgAlternative.set_charset(CHARSET) msgRoot.attach(msgAlternative) text = kwargs['plaintext'] msgText = MIMEText(__uni2iso(text), 'plain', CHARSET) msgAlternative.attach(msgText) html = kwargs['htmltext'] html = html.replace('UTF-8', CHARSET) msgText = MIMEText(__uni2iso(html), 'html', CHARSET) msgAlternative.attach(msgText) for img in kwargs.get('images', []): __mimeImage(img, msgRoot) for at in kwargs.get('attachements', []): __mimeData(at, msgRoot) return msgRoot
def send_assigned_mail(query_object): try: fromaddr = "*****@*****.**" to_list = User.objects.filter(groups__name='admin') toaddr = [i.username + '@gmail.com' for i in to_list] toaddr.append(query_object.created_by + '@gmail.com') toaddr.append(query_object.assigned_to.username + '@gmail.com') print toaddr msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = ', '.join(toaddr) msg['Subject'] = 'ticket Id: [%s]%s' % (query_object.id, query_object.created_by) body = "The ticket with ticket number:%s has been ASSIGNED to %s kindly check the dashboard for further " \ "details" % (query_object.id, query_object.assigned_to.username) msg.add_header("Message-ID", query_object.email_msg_id) msg.add_header("In-Reply-To", query_object.email_msg_id) msg.add_header("References", query_object.email_msg_id) msg.attach(MIMEText(body, 'plain')) server = smtplib.SMTP('10.17.0.10', 25) server.ehlo() server.starttls() server.ehlo() text = msg.as_string() server.sendmail(fromaddr, toaddr, text) except Exception, e: print e.args
def email_user(email_file): smtp_server = process_config('email_server', 'server') smtp_port = process_config('email_server', 'port') fromaddr = process_config('email_server', 'from') reply_to = process_config('email_server', 'reply') rec_user = process_config('email_user', 'emailaddr') msg = MIMEMultipart() server = smtplib.SMTP(smtp_server, smtp_port) rec_user = rec_user.split(',') sub = 'NeCTAR Infrastructure Resource usage' msg['From'] = fromaddr msg['BCC'] = ",".join(rec_user) msg['Subject'] = sub f = open(email_file, 'r') html_data = [i for i in f] body = "".join(html_data) ''' if os.path.exists(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) msg.attach(MIMEText(body, 'html')) text = msg.as_string() server.sendmail(fromaddr, rec_user, text) server.quit() else: ''' msg.add_header('reply-to', reply_to) msg.attach(MIMEText(body, 'html')) text = msg.as_string() server.sendmail(fromaddr, rec_user, text) server.quit()
def send_email(email, sujet, msg): tolog_info("Envoi du mail '%s' à %s..." % (sujet, email)) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() msgMail = MIMEMultipart() msgMail['From'] = addEmailFrom msgMail['To'] = email msgMail['Subject'] = sujet msgMail.add_header('reply-to', addEmailAdm) # addEmailNPR msgMail.attach(MIMEText(msg, 'plain', 'utf-8')) body = msgMail.as_string() server.login(addEmailFrom, addEmailPass) server.sendmail(addEmailFrom, email, body) server.quit() tolog_info_verb("...envoi de l'email OK") return ()
def send_mail(server, from_address, from_name, to_address, subject, body_arg, return_addr, tls): msg = MIMEMultipart('alternative') msg['To'] = to_address msg['Date'] = formatdate(localtime = True) msg['Subject'] = subject msg.add_header('reply-to', return_addr) msg.add_header('from', from_name + "<" + from_address + ">") part1 = MIMEText(body_arg, 'plain') part2 = MIMEText(body_arg, 'html') msg.attach(part1) msg.attach(part2) try: smtp = smtplib.SMTP(server) smtp.set_debuglevel(VERBOSE) smtp.sendmail(from_address, to_address, msg.as_string()) smtp.quit() except smtplib.SMTPException: print FAIL + "[-] Error: unable to send email to ", to_address, ENDC
def send_mail(server, from_address, from_name, to_address, subject, body_arg, return_addr, tls): msg = MIMEMultipart('alternative') msg['To'] = to_address msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.add_header('reply-to', return_addr) msg.add_header('from', from_name + "<" + from_address + ">") part1 = MIMEText(body_arg, 'plain') part2 = MIMEText(body_arg, 'html') msg.attach(part1) msg.attach(part2) try: smtp = smtplib.SMTP(server) smtp.set_debuglevel(VERBOSE) smtp.sendmail(from_address, to_address, msg.as_string()) smtp.quit() except smtplib.SMTPException: print FAIL + "[-] Error: unable to send email to ", to_address, ENDC
def send_server_mail(sender, recipients, subject, text, bcc=[], reply_to="",server="localhost"): """ Send an e-mail through the server's email service. args: sender: address for the sender. recipients: iterable of email addresses of the recipients. subject: email subject. text: email text. server: the server that is going to send the message. """ #from email.MIMEBase import MIMEBase from email.Utils import formatdate #import os msg = MIMEMultipart() msg['From'] = sender msg['To'] = ','.join(recipients) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text,'html','utf-8')) if reply_to: msg.add_header('reply-to', reply_to) smtp = smtplib.SMTP(server) smtp.sendmail(sender, recipients+bcc, msg.as_string()) smtp.quit()
def send_email(status, msg_table=''): try: time_utc = datetime.now(timezone('UTC')) time_ist = time_utc.astimezone(timezone('Asia/Kolkata')) msgid = '<*****@*****.**>' msg = MIMEMultipart() msg['From'] = EMAIL_FROMADDR msg['To'] = ",".join(EMAIL_TOADDR) msg['Cc'] = ",".join(EMAIL_CCADDR) msg.add_header("In-Reply-To", msgid) msg.add_header("References", msgid) msg['Subject'] = "Monitoring production server" msg.attach(MIMEText(msg_table, 'html')) server = smtplib.SMTP(EMAIL_SMTP_HOST, EMAIL_SMTP_PORT) server.starttls() server.login(EMAIL_FROMADDR, EMAIL_HOST_PASSWORD) text = msg.as_string() recipients_list = EMAIL_TOADDR + EMAIL_CCADDR server.sendmail(EMAIL_FROMADDR, recipients_list, text) server.quit() except Exception as em: traceback.print_exc() print "Exception in email ", str(em)
def send_mail(send_from, send_to, subject, text, files=[], server="smtp.gmail.com:587"): assert type(send_to) == list assert type(files) == list msg = MIMEMultipart() msg['From'] = send_from + ' <' + smtp_login_mail + '>' msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text)) msg.add_header('reply-to', send_from) 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.ehlo() smtp.starttls() smtp.ehlo smtp.login('baskar.krishnan at gmail.com', 'password') smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close() files = ['Config.ini', 'mail_ini.txt'] send_to = ['baskar.krishnan at gmail.com'] send_mail('mahadevan.m at gmail.com', send_to, 'test subject', 'body matter', files)
def send_mail(send_from, password, send_to, subject, body, files=[], server="smtp.gmail.com:587"): assert type(send_to)==list assert type(files)==list msg = MIMEMultipart('alternative') msg.add_header('reply-to', '123456789') msg['From'] = send_from + ' <' + '123456789' + '>' msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(body, '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) smtp = smtplib.SMTP(server) smtp.ehlo() smtp.starttls() smtp.ehlo smtp.login(send_from, password) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def mail(self): """ Use the add header message and then the get_all message to add multiple recipients """ msg = MIMEMultipart() msg.add_header('From', self.fromAddress) msg.add_header('Subject', self.subject) #Loop over csv string to add recipients for emailAddress in self.to.split(','): msg.add_header('To', emailAddress) msg.attach(MIMEText(self.text)) if self.attach != None: part = MIMEBase('application', 'octet-stream') part.set_payload(open(self.attach, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(self.attach)) msg.attach(part) try: mailServer = smtplib.SMTP(self.server, self.port) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() #Assumes the password is obfuscated tmp = deObfuscateString(self.passwd) mailServer.login(self.fromAddress, tmp) mailServer.sendmail(self.fromAddress, msg.get_all(('To')), msg.as_string()) # Should be mailServer.quit(), but that crashes... except smtplib.SMTPAuthenticationError as inst: output = "ERROR GENERATED: EmailWrapper.Mail\n" output += "Exception Type: " + str(type(inst)) + "\n" output += "Exception: " + str(inst) + "\n" self.errString += output + '\n' self.hasErrors = True print self.errString except Exception as inst: output = "ERROR GENERATED:\n" output += "Exception Type: " + str(type(inst)) + "\n" output += "Exception: " + str(inst) + "\n" self.errString += output + '\n' self.hasErrors = True print self.errString finally: mailServer.close()
def send_email(params): msg = MIMEMultipart() msg['From'] = params['from'] msg['To'] = str(params['to']) msg['Subject'] = params['subject'] cc = None if 'cc' in params: cc = params['cc'] bcc = None if 'bcc' in params: bcc = params['bcc'] if 'body' in params: msg.attach(MIMEText(params['body'], 'html')) if 'attachments' in params: if len('attachments') > 0: for filename, data in params['attachments'].iteritems(): attachment = MIMEApplication(data, 'pdf') attachment.add_header('Content-Disposition', 'attachment; filename=%s' % filename) msg.attach(attachment) reply_to = None if 'reply_to' in params: msg.add_header('Reply-To', params['reply_to']) # build dest list with cc, bcc is specified to = [str(params['to'])] if cc: 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: if type(bcc) in [str, unicode]: bcc = [bcc] to += bcc server = smtplib.SMTP_SSL(app.config['MAIL_SERVER'], app.config['MAIL_PORT']) server.login(app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']) text = msg.as_string() try: server.sendmail(msg['From'], to, text) except Exception as e: print('Error:', e) finally: server.quit()
def sendMail_sendmail(self): """ sendmail specific function for sending the email """ message = MIMEMultipart('alternative') message.add_header('Subject', self.subjectLine) message.add_header('From', self.fromLine) message.add_header('To', ", ".join(self.toLine)) message.attach(MIMEText(self.body)) s = subprocess.Popen('sendmail ' + " ".join(self.toLine), shell=True, stdin=subprocess.PIPE) s.communicate(message.as_string())
def sendkillermail(filepath,name,friends,lastwords,plattform): message = MIMEMultipart() message.add_header('Subject', 'new suicidemachine user') message.add_header('From','*****@*****.**') message.add_header('To','*****@*****.**') message.attach(MIMEText(name + "\n" + friends + "\n" + lastwords + "\n" + plattform)) # plain text alternative part = MIMEBase('application', "octet-stream") part.set_payload( open(filepath,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(filepath)) message.attach(part) server = smtplib.SMTP("moddr.net") try: failed = server.sendmail("*****@*****.**", "*****@*****.**", message.as_string()) server.close() except Exception, e: errorMsg = "Unable to send email. Error: %s" % str(e)
def send_email(filename): msgsubject = 'Workout from Rowsberry Pi' htmlmsgtext = """This is a workout recorded with Rowsberry Pi</br> Yup. Yup. Yup.</br>""" msgtext = htmlmsgtext.replace('<b>', '').replace('</b>', '').replace( '<br>', "\r").replace('</br>', "\r").replace('<br/>', "\r").replace('</a>', '') msgtext = re.sub('<.*?>', '', msgtext) msg = MIMEMultipart() msg.preamble = 'This is a multi-part message in MIME format.\n' msg.epilogue = '' body = MIMEMultipart('alternative') body.attach(MIMEText(msgtext)) body.attach(MIMEText(htmlmsgtext, 'html')) msg.attach(body) part = MIMEBase('application', "octet-stream") part.set_payload(open(filename, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(filename)) msg.attach(part) msg.add_header('From', email_fromaddress) msg.add_header('To', email_recipients) msg.add_header('Subject', msgsubject) # The actual email sendy bits server = smtplib.SMTP('%s:%s' % (email_host, email_port)) server.set_debuglevel(True) if email_use_tls: server.starttls() server.login(email_host_user, email_host_password) if not isinstance(email_recipients, list): email_recipients = [email_recipients] server.sendmail(msg['From'], email_recipients, msg.as_string()) server.quit() #bye bye
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 if isinstance(filename, unicode): filename = filename.encode('utf-8') msg.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', filename)) outer.attach(msg) return outer.as_string()
body.attach(MIMEText(msgtext)) body.attach(MIMEText(htmlmsgtext, 'html')) msg.attach(body) if 'attachments' in globals( ) and len('attachments') > 0: # are there attachments? for filename in attachments: f = filename 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) msg.add_header('From', fromaddr) msg.add_header('To', toaddr) msg.add_header('Subject', msgsubject) msg.add_header('Reply-To', replyto) # The actual email sendy bits server = smtplib.SMTP(host) server.set_debuglevel(False) # set to True for verbose output try: # gmail expect tls server.starttls() server.login(username, password) server.sendmail(msg['From'], [msg['To']], msg.as_string()) print 'Email sent' server.quit() # bye bye except: