def __init__(self, sender='', recipients=[], subject='', from_defs=0, alternative=0, reply_to=None): from email.mime.multipart import MIMEMultipart from email import Charset Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') if type(recipients) == str: recipients = recipients.replace(';', ',') recipients = recipients.split(',') self.from_defs = from_defs self.sender = sender self.reply_to = reply_to or sender self.recipients = recipients self.subject = subject self.msg_root = MIMEMultipart('mixed') self.msg_multipart = MIMEMultipart('alternative') self.msg_root.attach(self.msg_multipart) self.cc = []
def __init__(self, sender='', recipients=(), subject='', alternative=0, reply_to=None, cc=(), email_account=None): from email.mime.multipart import MIMEMultipart from email import Charset Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') if isinstance(recipients, basestring): recipients = recipients.replace(';', ',').replace('\n', '') recipients = split_emails(recipients) # remove null recipients = filter(None, (strip(r) for r in recipients)) self.sender = sender self.reply_to = reply_to or sender self.recipients = recipients self.subject = subject self.msg_root = MIMEMultipart('mixed') self.msg_multipart = MIMEMultipart('alternative') self.msg_root.attach(self.msg_multipart) self.cc = cc or [] self.html_set = False self.email_account = email_account
def MIME_mail_build(src_name, src_mail, dest_name, dest_mail, title, mail_body): # Override python's weird assumption that utf-8 text should be encoded with # base64, and instead use quoted-printable (for both subject and body). I # can't figure out a way to specify QP (quoted-printable) instead of base64 in # a way that doesn't modify global state. :-( if six.PY2: from email import Charset # pylint: disable=no-name-in-module Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') # pylint: disable=undefined-variable, no-member # This example is of an email with text and html alternatives. multipart = MIMEMultipart('alternative') # We need to use Header objects here instead of just assigning the strings in # order to get our headers properly encoded (with QP). # You may want to avoid this if your headers are already ASCII, just so people # can read the raw message without getting a headache. multipart['Subject'] = Header(title.encode('utf-8'), 'UTF-8').encode() multipart['Date'] = utils.formatdate() multipart['To'] = Header(dest_name.encode('utf-8'), 'UTF-8').encode() + " <" + dest_mail + ">" multipart['From'] = Header(src_name.encode('utf-8'), 'UTF-8').encode() + " <" + src_mail + ">" multipart['X-Mailer'] = "fnord" multipart.attach(MIMEText(mail_body.encode('utf-8'), 'plain', 'UTF-8')) if six.PY2: multipart_as_bytes = six.binary_type(multipart.as_string()) else: multipart_as_bytes = multipart.as_bytes() # pylint: disable=no-member return BytesIO(multipart_as_bytes) # pylint: disable=no-member
def mail(to, to_name, subject, message): gmail_user = '******' gmail_pwd = 'FDSfh2@##52dsdmjb!@%@#jfdkwvmnr' # Example address data from_address = [u'Goals Server', '*****@*****.**'] recipient = [to_name, to] subject = subject # body html = textwrap.dedent(message) text = textwrap.dedent(message) # Default encoding mode set to Quoted # printable. Acts globally! Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') # 'alternative’ MIME type – HTML and plain text bundled in one e-mail message msg = MIMEMultipart('alternative') msg['Subject'] = "%s" % Header(subject, 'utf-8') # Only descriptive part of recipient and sender shall be encoded, not the email address msg['From'] = "\"%s\" <%s>" % (Header(from_address[0], 'utf-8'), from_address[1]) msg['To'] = "\"%s\" <%s>" % (Header(recipient[0], 'utf-8'), recipient[1]) # Attach both parts htmlpart = MIMEText(html, 'html', 'UTF-8') textpart = MIMEText(text, 'plain', 'UTF-8') msg.attach(htmlpart) msg.attach(textpart) # Create a generator and flatten message object to 'file’ str_io = StringIO() g = Generator(str_io, False) g.flatten(msg)
def send_email(to_email,subject,message): # send the message smtp = SMTP() smtp.connect('smtp.mandrillapp.com', 587) smtp.login(os.environ.get('MANDRILL_USERNAME'), os.environ.get('MANDRILL_APIKEY')) from_addr = "Tindfell <*****@*****.**>" to_addr = [to_email] date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" ) Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') msg = MIMEMultipart("alternative") msg['From'] = Header(from_addr.encode('utf-8'), 'UTF-8').encode() msg['To'] = Header(', '.join(to_addr).encode('utf-8'), 'UTF-8').encode() msg['Subject'] = Header(subject.encode('utf-8'), 'UTF-8').encode() msg.attach(MIMEText(message.encode('utf-8'),'plain','utf-8')) #msg.attach(MIMEText(message.encode('utf-8'),'html','utf-8')) io = StringIO() g = Generator(io, False) # second argument means "should I mangle From?" g.flatten(msg) # For Degubbing #print io.getvalue() # send the message! smtp.sendmail(from_addr, to_addr, io.getvalue()) smtp.quit() return
def fix_garbled_mail(): """ 8bit seems to cause buggy emails in Hebrew. revert back to base64""" # In django 1.5, this prevents BASE64: from django.core.mail import message # let's undo it: from email import Charset Charset.add_charset('utf-8', Charset.SHORTEST, Charset.BASE64, 'utf-8')
def __init__(self, sender='', recipients=(), subject='', alternative=0, reply_to=None, cc=(), email_account=None, expose_recipients=None): from email.mime.multipart import MIMEMultipart from email import Charset Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') if isinstance(recipients, basestring): recipients = recipients.replace(';', ',').replace('\n', '') recipients = split_emails(recipients) # remove null recipients = filter(None, (strip(r) for r in recipients)) self.sender = sender self.reply_to = reply_to or sender self.recipients = recipients self.subject = subject self.expose_recipients = expose_recipients self.msg_root = MIMEMultipart('mixed') self.msg_multipart = MIMEMultipart('alternative') self.msg_root.attach(self.msg_multipart) self.cc = cc or [] self.html_set = False self.email_account = email_account or get_outgoing_email_account()
def MIME_mail_build(src_name, src_mail, dest_name, dest_mail, title, mail_body): # Override python's weird assumption that utf-8 text should be encoded with # base64, and instead use quoted-printable (for both subject and body). I # can't figure out a way to specify QP (quoted-printable) instead of base64 in # a way that doesn't modify global state. :-( Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') # This example is of an email with text and html alternatives. multipart = MIMEMultipart('alternative') # We need to use Header objects here instead of just assigning the strings in # order to get our headers properly encoded (with QP). # You may want to avoid this if your headers are already ASCII, just so people # can read the raw message without getting a headache. multipart['Subject'] = Header(title.encode('utf-8'), 'UTF-8').encode() multipart['Date'] = rfc822_date() multipart['To'] = Header(dest_name.encode('utf-8'), 'UTF-8').encode() + \ " <" + dest_mail + ">" multipart['From'] = Header(src_name.encode('utf-8'), 'UTF-8').encode() + \ " <" + src_mail + ">" multipart['X-Mailer'] = "fnord" textpart = MIMEText(mail_body.encode('utf-8'), 'plain', 'UTF-8') multipart.attach(textpart) return StringIO.StringIO(multipart.as_string())
def send(to, subject, text, params={}, bcc=[], cc=[]): global emailThread Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') text = u"<html>" + text + u"</html>" msg = MIMEText(text, 'html', 'utf-8') msg['Subject'] = subject msg['From'] = config.mail_sender() if not 'Sender' in msg: msg['Sender'] = config.get('return_path') msg['To'] = (','.join(to)) if isinstance(to, (list)) else to if len(cc) > 0: msg['Cc'] = (','.join(cc)) if isinstance(cc, (list)) else cc for key in params.keys(): msg[key] = params[key] send_to = set((to if isinstance(to, (list)) else [ to ]) +\ (cc if isinstance(cc, (list)) else [ cc ]) +\ (bcc if isinstance(bcc, (list)) else [ bcc ])) # Vlozime email do fronty queueLock.acquire() emailQueue.put(emailData(msg['Sender'], send_to, msg.as_string())) if emailThread and emailThread.isAlive(): queueLock.release() else: queueLock.release() emailThread = sendThread() emailThread.start()
def send_email(from_address, recipient, subject, text): # Default encoding mode set to Quoted Printable. Acts globally! Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') # 'alternative’ MIME type – HTML and plain text bundled in one e-mail message msg = MIMEMultipart('alternative') msg['Subject'] = "%s" % Header(subject, 'utf-8') # Only descriptive part of recipient and sender shall be encoded, not the email address msg['From'] = "\"%s\" <%s>" % (Header(from_address[0], 'utf-8'), from_address[1]) msg['To'] = "\"%s\" <%s>" % (Header(recipient[0], 'utf-8'), recipient[1]) # Attach both parts textpart = MIMEText(text, 'plain', 'UTF-8') msg.attach(textpart) # Create a generator and flatten message object to 'file’ str_io = StringIO() g = Generator(str_io, False) g.flatten(msg) # str_io.getvalue() contains ready to sent message # Optionally - send it – using python's smtplib # or just use Django's smtpObj = smtplib.SMTP('smtp.u-psud.fr') smtpObj.sendmail(from_address[1], recipient[1], str_io.getvalue()) #except SMTPException: # print "Error: unable to send email" # raise Exception("Mail non envoyé") #end def #end class
def mime_message(msg_subject, msg_from, msg_to, \ plain_msg_body, html_msg_body=None, encoding="utf-8"): if not plain_msg_body: raise Exception("Plain text body is mandatory!") Charset.add_charset(encoding, Charset.QP, Charset.QP, encoding) if not html_msg_body: msg = MIMEText(plain_msg_body.encode(encoding), "plain", encoding.upper()) else: msg = MIMEMultipart("alternative") msg.attach( MIMEText(plain_msg_body.encode(encoding), "plain", encoding.upper())) msg.attach( MIMEText(html_msg_body.encode(encoding), "html", encoding.upper())) if msg_subject: msg["subject"] = Header(msg_subject.encode(encoding), encoding.upper()) if msg_from: msg["from"] = encode_address(msg_from, encoding) if msg_to: msg["to"] = encode_address(msg_to, encoding) return msg
def MailSender(name, email): mFrom = [u'ΔΔΕ %s' % SETTINGS['dide_place'], SETTINGS['email_dide']] mRecipient = [name, email] mSubject = u'Ενημέρωση στοιχείων του φακέλου σας.' mHtml = u"""<p>Πραγματοποιήθηκε ενημέρωση στοιχείων του φακέλου σας, στο """ mHtml += u"""σύστημα προσωπικού της ΔΔΕ.</p>""" mHtml += u"""<p><a href="http://its.dide.dod.sch.gr">Συνδεθείτε στο """ mHtml += u"""σύστημα για να δείτε τις αλλαγές</a></p>""" mHtml += u"""<p>Απο την ΔΔΕ %s</p>""" % SETTINGS['dide_place'] Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') msg = MIMEMultipart('alternative') msg['Subject'] = "%s" % Header(mSubject, 'utf-8') msg['From'] = "\"%s\" <%s>" % (Header(mFrom[0], 'utf-8'), mFrom[1]) msg['To'] = "\"%s\" <%s>" % (Header(mRecipient[0], 'utf-8'), mRecipient[1]) htmlpart = MIMEText(mHtml, 'html', 'UTF-8') msg.attach(htmlpart) str_io = StringIO() g = Generator(str_io, False) g.flatten(msg) s = smtplib.SMTP(settings.EMAIL_HOST, 587) s.ehlo() s.starttls() s.ehlo() s.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD) s.sendmail(SETTINGS['email_dide'], email, str_io.getvalue())
def __init__(self, toName, toAddr, ticketID): # Sender information self.fromName = 'Example Example' self.fromAddr = '*****@*****.**' # Receiver/s information self.toName = toName self.toAddr = [] self.toAddr.append(toAddr) # Support for multiple targets from csv file, no comma #with open('testlist.csv', 'rb') as mysecondfile: #self.csvdata = csv.reader(mysecondfile, delimiter=' ', quotechar='|') #for row in csvdata: #receivers.append(row) self.ticketID = ticketID # Subject of mail self.subject = 'Ticket ' + self.ticketID + ' successfully purchased.' # Variables to HTML template self.context = {'name': toName, 'qr_code': ticketID} self.msg = MIMEMultipart('mixed') self.inline = MIMEMultipart('alternative') # Local SMTP - server - Requires working one e.g Postfix self.server = smtplib.SMTP('127.0.0.1', 25) # Global charset to UTF-8 Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')
def MIME_mail_build(src_name, src_mail, dest_name, dest_mail, title, mail_body): # Override python's weird assumption that utf-8 text should be encoded with # base64, and instead use quoted-printable (for both subject and body). I # can't figure out a way to specify QP (quoted-printable) instead of base64 in # a way that doesn't modify global state. :-( Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') # This example is of an email with text and html alternatives. multipart = MIMEMultipart('alternative') # We need to use Header objects here instead of just assigning the strings in # order to get our headers properly encoded (with QP). # You may want to avoid this if your headers are already ASCII, just so people # can read the raw message without getting a headache. multipart['Subject'] = Header(title.encode('utf-8'), 'UTF-8').encode() multipart['Date'] = rfc822_date() multipart['To'] = Header(dest_name.encode('utf-8'), 'UTF-8').encode() + \ " <" + dest_mail + ">" multipart['From'] = Header(src_name.encode('utf-8'), 'UTF-8').encode() + \ " <" + src_mail + ">" multipart['X-Mailer'] = "fnord" # Attach the parts with the given encodings. # html = '<html>...</html>' # htmlpart = MIMEText(html.encode('utf-8'), 'html', 'UTF-8') # multipart.attach(htmlpart) textpart = MIMEText(mail_body.encode('utf-8'), 'plain', 'UTF-8') multipart.attach(textpart) return StringIO.StringIO(multipart.as_string())
def send_mail(m, subject, target, crici_state): # Example address data # from_address = [u'⌘Tomek Kopczuk⌘', '*****@*****.**'] # recipient = [u'Those #!@', '*****@*****.**'] # Example body # text = u'Unicode°\nTest⏎' # Default encoding mode set to Quoted Printable. Acts globally! Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') # 'alternative’ MIME type – HTML and plain text bundled in one e-mail message msg = MIMEMultipart('alternative') msg['Subject'] = "%s" % Header(subject, 'utf-8') # Only descriptive part of recipient and sender shall be encoded, not the email address # msg['From'] = "\"%s\" <%s>" % (Header(from_address[0], 'utf-8'), from_address[1]) msg['To'] = target # Attach both parts textpart = MIMEText(m.encode('utf-8'), _charset='utf-8') msg.attach(textpart) # print str_io.getvalue() # print msg.as_string() if (critc[0] == 'GK' and crici_state): msg['Importance'] = 'High' p = subprocess.Popen(['/usr/sbin/sendmail', '-t' ], stdin = subprocess.PIPE) p.communicate(msg.as_string()) return True
def MIME_mail_build(src_name, src_mail, dest_name, dest_mail, title, mail_body): # Override python's weird assumption that utf-8 text should be encoded with # base64, and instead use quoted-printable (for both subject and body). I # can't figure out a way to specify QP (quoted-printable) instead of base64 in # a way that doesn't modify global state. :-( Charset.add_charset("utf-8", Charset.QP, Charset.QP, "utf-8") # This example is of an email with text and html alternatives. multipart = MIMEMultipart("alternative") # We need to use Header objects here instead of just assigning the strings in # order to get our headers properly encoded (with QP). # You may want to avoid this if your headers are already ASCII, just so people # can read the raw message without getting a headache. multipart["Subject"] = Header(title.encode("utf-8"), "UTF-8").encode() multipart["Date"] = rfc822_date() multipart["To"] = Header(dest_name.encode("utf-8"), "UTF-8").encode() + " <" + dest_mail + ">" multipart["From"] = Header(src_name.encode("utf-8"), "UTF-8").encode() + " <" + src_mail + ">" multipart["X-Mailer"] = "fnord" textpart = MIMEText(mail_body.encode("utf-8"), "plain", "UTF-8") multipart.attach(textpart) return StringIO.StringIO(multipart.as_string())
def _assemble_message(self, message): subject = SUBJECT recipient = RECIPIENT from_address = FROMADDR text = message.decode('utf-8') html = u'<html><body>%s</body></html>' % text Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') multipart = MIMEMultipart('alternative') multipart['Subject'] = Header(subject.encode('utf-8'), 'UTF-8').encode() multipart['To'] = Header(recipient.encode('utf-8'), 'UTF-8').encode() multipart['From'] = Header(from_address.encode('utf-8'), 'UTF-8').encode() htmlpart = MIMEText(html.encode('utf-8'), 'html', 'UTF-8') multipart.attach(htmlpart) textpart = MIMEText(text.encode('utf-8'), 'plain', 'UTF-8') multipart.attach(textpart) io = StringIO() g = Generator(io, False) # second argument means "should I mangle From?" g.flatten(multipart) return io.getvalue()
def send_message_notification(sender, instance, **kwargs): """ Send email when user receives a new message. This email contains the full text and a link to read it online. We trigger this when a MessageRecipient is saved and not when a Message is saved because umessages first saves a message and then adds its recipients, so when a Message is saved, it doesn't yet have a list of recipients. """ if not instance.user.email: # Email can be missing for users registered with Twitter # or LinkedIn return params = {"sender": instance.message.sender.username, "body": instance.message.body} message_url_path = reverse("userena_umessages_detail", kwargs={"username": params["sender"]}) params["message_url"] = "%s://%s%s" % (get_protocol(), Site.objects.get_current(), message_url_path) subject = _(u"New message from %(sender)s on Imagination For People") % params message = render_to_string("umessages/message_notification.txt", params) recipient = instance.user.email # XXX Resets the Content-Transfer-Encoding in email header # Avoids bad encoding of UTF-8 body # See https://code.djangoproject.com/ticket/3472 from email import Charset Charset.add_charset("utf-8", Charset.SHORTEST, "utf-8", "utf-8") send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [recipient])
def create_message( addr_from='*****@*****.**', addr_to='*****@*****.**', message_id=None, subject='subject', body='body', subtype='plain', encoding="utf-8" ): ''' Creating Message :rtype: SafeMIMTExt(MIMEMixin, email.mime.text.MIMETex) - `as_string()` method serializes into string ''' message_id = message_id or uuid.uuid1().hex if encoding == "shift_jis": #: DoCoMo #: TODO chekck message encoding and convert it Charset.add_charset( 'shift_jis', Charset.QP, Charset.BASE64, 'shift_jis') Charset.add_codec('shift_jis', 'cp932') message = SafeMIMEText(body, subtype, encoding) message['Subject'] = subject message['From'] = addr_from message['To'] = addr_to message['Message-ID'] = message_id return message
def send_mail(m, subject, target, crici_state): # Example address data # from_address = [u'⌘Tomek Kopczuk⌘', '*****@*****.**'] # recipient = [u'Those #!@', '*****@*****.**'] # Example body # text = u'Unicode°\nTest⏎' # Default encoding mode set to Quoted Printable. Acts globally! Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') # 'alternative’ MIME type – HTML and plain text bundled in one e-mail message msg = MIMEMultipart('alternative') msg['Subject'] = "%s" % Header(subject, 'utf-8') # Only descriptive part of recipient and sender shall be encoded, not the email address # msg['From'] = "\"%s\" <%s>" % (Header(from_address[0], 'utf-8'), from_address[1]) msg['To'] = target # Attach both parts textpart = MIMEText(m.encode('utf-8'), _charset='utf-8') msg.attach(textpart) # print str_io.getvalue() # print msg.as_string() if (critc[0] == 'GK' and crici_state): msg['Importance'] = 'High' p = subprocess.Popen(['/usr/sbin/sendmail', '-t'], stdin=subprocess.PIPE) p.communicate(msg.as_string()) return True
def send_mail(msg_body,subject): global smtp_password, smtp_username,email_receivers # Addresses to Send on print "Drafing Mail body" #Mail Body starts text_body = "" top_heading = "<b>Summary is as below:</b><br/>" text_body = msg_body #Returned from Processing Stage text_body = top_heading + text_body # Default encoding mode set to Quoted Printable. Acts globally! Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') # 'alternative’ MIME type – HTML and plain text bundled in one e-mail message msg = MIMEMultipart('alternative') msg['Subject']=subject # Only descriptive part of recipient and sender shall be encoded, not the email address msg['From'] = fromaddr msg['To'] = toaddr # Attach both parts text_body = MIMEText(text_body, 'html', 'UTF-8') msg.attach(text_body) # Create a generator and flatten message object to 'file’ str_io = StringIO() g = Generator(str_io, False) g.flatten(msg) # str_io.getvalue() contains ready to sent message # Optionally - send it – using python's smtplib s = smtplib.SMTP('smtp.gmail.com', 587) s.ehlo() s.starttls() #This is incase gmail connectivity dont happen at once. while True: try: s.login(smtp_username, smtp_password) #Log into SMTP Server for toaddr in email_receivers: #Loop to go through entire receiver list and send them mail one by one. s.sendmail(fromaddr, toaddr, str_io.getvalue()) break except Exception as x: print x s.quit() #Print when the last mail was sent, for debug purpose or to check who failed? the script or the mail ? ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') print "Mail Sent @ "+str(st) print "\n\n"
def send_mail(command_id, command_raw, payload, rec): """Sent the fetched information as Mail to the receiver. Parameter command_id: Name of the executed command command_raw: Complete command with arguments payload: The HTML page to return rec: The Mail receiver Return: True for OK, False for Failure """ # Override python's weird assumption that utf-8 text should be encoded with base64 Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') # First format as a message # Create the container (outer) email message. msg = MIMEMultipart() msg['Subject'] = 'Mail2Web Fetched: ' + command_id # me == the sender's email address msg['From'] = Opts['sender'] msg['To'] = rec # Plain text as explanation explanation = "This is the demon slave\n" + \ "I executed for you:\n" + command_raw + \ "\n\nHave fun!\n" + \ "To reach some admin, please mailto: admin@thishost\n" + \ "This mail address only takes commands for fetching web sites\n" +\ "\nPlease be also remindad that this is an beta service. " +\ "This means particularly that I am currently logging and " +\ "inspecting all accesses." # This is they way also Softbank Phones understand it msg_explanation = MIMEText(explanation, "plain", "utf-8") # And the explanation as text msg_explanation.add_header('Content-Disposition', 'inline') # Show message inline msg.attach(msg_explanation) # And our HTML we want to send, and it's an attachment msg_payload = MIMEText(payload, "html", "utf-8") msg_payload.add_header('Content-Disposition', 'attachment; filename="result.html"') msg.attach(msg_payload) # Send the email via our own SMTP server. # Debug # print msg.as_string() # return False pinfo("Will send the result now to " + rec + " ...") try: # Open Connection; Catch exceptions smtp = smtplib.SMTP(Opts['smtp_server_host'], Opts['smtp_server_port']) except (smtplib.SMTPException, socket.error), detail: perror("Establishing SMTP connection to " + \ Opts['smtp_server_host'] + ":" + Opts['smtp_server_port'] + \ " failed: " + str(detail)) return False
def send_mailx(text_content, html_content, subject, to_, email_from_, mail_host, mail_port): ''' generic smtp function. sends email based on arguments ''' try: text_content = formatted_text_body.format(str(text_content)) html_content = html.format(str(html_content)) if isinstance(to_, list): to_ = ', '.join(to_) # Override python's weird assumption that utf-8 text should be encoded with # base64, and instead use quoted-printable (for both subject and body). I # can't figure out a way to specify QP (quoted-printable) instead of base64 in # a way that doesn't modify global state. :-( Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = email_from_ msg['To'] = to_ # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(text_content.encode('utf-8'), 'plain', 'UTF-8') part2 = MIMEText(html_content.encode('utf-8'), 'html', 'UTF-8') # 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. msg.attach(part1) msg.attach(part2) mail_host = mail_host mail_port = mail_port server = smtplib.SMTP(host=mail_host, port=mail_port) server.sendmail('no-reply@chikka', to_, msg.as_string()) server.quit() except Exception, e: # print e import traceback print traceback.format_exc()
def send_mail(command_id, command_raw, payload, rec): """Sent the fetched information as Mail to the receiver. Parameter command_id: Name of the executed command command_raw: Complete command with arguments payload: The HTML page to return rec: The Mail receiver Return: True for OK, False for Failure """ # Override python's weird assumption that utf-8 text should be encoded with base64 Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') # First format as a message # Create the container (outer) email message. msg = MIMEMultipart() msg['Subject'] = 'Mail2Web Fetched: ' + command_id # me == the sender's email address msg['From'] = Opts['sender'] msg['To'] = rec # Plain text as explanation explanation = "This is the demon slave\n" + \ "I executed for you:\n" + command_raw + \ "\n\nHave fun!\n" + \ "To reach some admin, please mailto: admin@thishost\n" + \ "This mail address only takes commands for fetching web sites\n" +\ "\nPlease be also remindad that this is an beta service. " +\ "This means particularly that I am currently logging and " +\ "inspecting all accesses." # This is they way also Softbank Phones understand it msg_explanation = MIMEText(explanation, "plain", "utf-8" ) # And the explanation as text msg_explanation.add_header('Content-Disposition', 'inline') # Show message inline msg.attach(msg_explanation) # And our HTML we want to send, and it's an attachment msg_payload = MIMEText(payload, "html", "utf-8") msg_payload.add_header('Content-Disposition', 'attachment; filename="result.html"') msg.attach(msg_payload) # Send the email via our own SMTP server. # Debug # print msg.as_string() # return False pinfo("Will send the result now to " + rec + " ...") try: # Open Connection; Catch exceptions smtp = smtplib.SMTP(Opts['smtp_server_host'], Opts['smtp_server_port']) except (smtplib.SMTPException, socket.error), detail: perror("Establishing SMTP connection to " + \ Opts['smtp_server_host'] + ":" + Opts['smtp_server_port'] + \ " failed: " + str(detail)) return False
def sendEmail(self, sender=None, recipient_list=None, subject=None, html=None, text=None, files=[]): # Default encoding mode set to Quoted Printable. Acts globally! Charset.add_charset("utf-8", Charset.QP, Charset.QP, "utf-8") if not sender: sender = self._sender sender_name, sender_addr = parseaddr(sender) if isinstance(recipient_list, basestring): rlist = recipient_list.split(",") if rlist and len(rlist) > 1: recipient_list = rlist else: recipient_list = [recipient_list] # 'alternative’ MIME type – HTML and plain text bundled in one e-mail message msg = MIMEMultipart() msg["From"] = formataddr((sender_name, sender_addr)) # msg['To'] = formataddr((recipient_name, recipient_addr)) msg["Subject"] = "%s" % Header(subject, "utf-8") # Attach both parts if html: htmlpart = MIMEText(html, "html", "UTF-8") msg.attach(htmlpart) if text: textpart = MIMEText(u"\n" + text.encode("UTF-8"), "plain", "UTF-8") msg.attach(textpart) if files: for f in files: if f: part = MIMEBase("application", "octet-stream") part.set_payload(open(f, "rb").read()) encoders.encode_base64(part) part.add_header("Content-Disposition", 'attachment; filename="{0}"'.format(os.path.basename(f))) msg.attach(part) try: s = smtplib.SMTP(self._smtp_server, self._smtp_port) s.ehlo() s.starttls() s.ehlo() s.login(self._user_login, self._user_password) ret = s.sendmail(sender, recipient_list, msg.as_string()) if ret: print "Sendmail returned: " + str(ret) except Exception, exc: print "Error occurred while sending: " + exc.message raise
def mail(to, to_name, subject, message): from cStringIO import StringIO from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.header import Header from email import Charset from email.generator import Generator import smtplib gmail_user = '******' gmail_pwd = 'FDSfh2@##52dsdmjb!@%@#jfdkwvmnr' # Example address data from_address = [u'Goals Server', '*****@*****.**'] recipient = [to_name, to] subject = subject # Example body html = message text = message # Default encoding mode set to Quoted Printable. Acts globally! Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') # 'alternative’ MIME type – HTML and plain text bundled in one e-mail message msg = MIMEMultipart('alternative') msg['Subject'] = "%s" % Header(subject, 'utf-8') # Only descriptive part of recipient and sender shall be encoded, not the email address msg['From'] = "\"%s\" <%s>" % (Header(from_address[0], 'utf-8'), from_address[1]) msg['To'] = "\"%s\" <%s>" % (Header(recipient[0], 'utf-8'), recipient[1]) # Attach both parts htmlpart = MIMEText(html, 'html', 'UTF-8') textpart = MIMEText(text, 'plain', 'UTF-8') msg.attach(htmlpart) msg.attach(textpart) # Create a generator and flatten message object to 'file’ str_io = StringIO() g = Generator(str_io, False) g.flatten(msg) # str_io.getvalue() contains ready to sent message # Optionally - send it – using python's smtplib # or just use Django's s = smtplib.SMTP('smtp.gmail.com', 587) s.ehlo() s.starttls() s.ehlo() s.login(gmail_user, gmail_pwd) s.sendmail("", recipient[1], str_io.getvalue())
def sendmail(sender, to, subject, contents, texttype='plain'): Charset.add_charset(encode, Charset.QP, Charset.QP, encode) msg = MIMEText(contents, texttype, encode) msg['Subject'] = Header(subject.encode(encode), encode).encode() msg['From'] = sender msg['To'] = ', '.join(to) s = SMTP('smtp.exmail.qq.com') s.ehlo('smtp.exmail.qq.com') s.set_debuglevel(False) s.login('*****@*****.**','GMvsBWKwZty47LG2') # access code is generated from web (settings->account->wechat code) try: s.sendmail(sender, to, msg.as_string()) finally: s.quit()
def send_emails(customers, template, host, port, user, password): """Send emails to customers. """ mails = [] for customer in customers: yaml = render_template(template, customer) data = load(yaml, Loader=Loader) # Use quoted printable instead of base64 Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') mail = MIMEText(data['body'], _charset='utf-8') mail['From'] = data['from'] mail['To'] = data['to'] mail['Subject'] = data['subject'] mails.append(mail) transfer_emails(mails, host, port, user, password)
def sendmail(sender, to, subject, contents, texttype='plain'): Charset.add_charset(encode, Charset.QP, Charset.QP, encode) msg = MIMEText(contents, texttype, encode) msg['Subject'] = Header(subject.encode(encode), encode).encode() msg['From'] = sender msg['To'] = ', '.join(to) s = SMTP('smtp.exmail.qq.com') s.ehlo('smtp.exmail.qq.com') s.set_debuglevel(False) s.login( '*****@*****.**', 'GMvsBWKwZty47LG2' ) # access code is generated from web (settings->account->wechat code) try: s.sendmail(sender, to, msg.as_string()) finally: s.quit()
def sendmail(sender, to, subject, contents, texttype='html'): Charset.add_charset(encode, Charset.QP, Charset.QP, encode) msg = MIMEText(contents, texttype, encode) msg['Subject'] = Header(subject.encode(encode), encode).encode() msg['From'] = sender msg['To'] = ', '.join(to) s = SMTP('smtp.exmail.qq.com') s.set_debuglevel(False) s.ehlo('smtp.exmail.qq.com') s.login('*****@*****.**', '1qaz@WSX') import pandas pandas.read_ex try: s.sendmail(sender, to, msg.as_string()) finally: s.quit()
def sendemail(subject, body): Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') msg = MIMEMultipart() msg['From'] = Header(fromaddr.encode('utf-8'), 'UTF-8').encode() msg['To'] = Header(toaddr.encode('utf-8'), 'UTF-8').encode() msg['Subject'] = Header(subject.encode('utf-8'), 'UTF-8').encode() msg.attach(MIMEText(body.encode('utf-8'), 'html', 'UTF-8')) try: server = smtplib.SMTP(smtpserver, smtpport) server.starttls() server.login(fromaddr, passwd) text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit() except Exception as e: dbgprint(e)
def mailNotify(title, jsonfile): title = "json file upload FAILED!!!:" + title fp = open(jsonfile, 'rb') body = fp.read() fp.close() Charset.add_charset('utf-8', Charset.QP, Charset.QP) msg = MIMEText(body, _charset='utf-8') msg['Subject'] = title msg['From'] = '*****@*****.**' msg['To'] = ', '.join(ToList) msg['Cc'] = ', '.join(CcList) s = smtplib.SMTP() s.connect("mail.srv") s.ehlo("hello") s.sendmail('*****@*****.**', ToList + CcList, msg.as_string()) s.close() print "json file upload failed,send notify mail done."
def send_html_email(user, pwd, recipient, subject, emailmsg): # Example address data global sendtoall from_address = [u'Weather Information', user] TO = recipient if type(recipient) is list else [recipient] # Example body html = u'Weather Notification :<br><br>' + emailmsg text = u'Weather Notification' # Default encoding mode set to Quoted Printable. Acts globally! Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') # 'alternative’ MIME type – HTML and plain text bundled in one e-mail message msg = MIMEMultipart('alternative') msg['Subject'] = "%s" % Header(subject, 'utf-8') # Only descriptive part of recipient and sender shall be encoded, not the email address msg['From'] = "\"%s\" <%s>" % (Header(from_address[0], 'utf-8'), from_address[1]) #msg['To'] = "\"%s\" <%s>" % (Header(recipient[0], 'utf-8'), recipient[1]) msg['To'] = "" if sendtoall == 1: for i in xrange(len(recipient)): msg['To'] = msg['To'] + str(recipient[i]) + ";" else: msg['To'] = adminemail # Attach both parts htmlpart = MIMEText(html, 'html', 'UTF-8') textpart = MIMEText(text, 'plain', 'UTF-8') msg.attach(htmlpart) msg.attach(textpart) # Create a generator and flatten message object to 'file’ str_io = StringIO() g = Generator(str_io, False) g.flatten(msg) # str_io.getvalue() contains ready to sent message # Send it – using python's smtplib s = smtplib.SMTP('smtp.gmail.com', 587) s.ehlo() s.starttls() s.ehlo() s.login(user, pwd) s.sendmail(user, TO, str_io.getvalue())
def apply(self, ui): if not self.message: self.message = ui.current_buffer.get_selected_message() mail = self.message.get_email() reply = MIMEMultipart() Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') if self.inline: # inline mode # set body text author = self.message.get_author()[0] mailcontent = '\nForwarded message from %s:\n' % author for line in self.message.accumulate_body().splitlines(): mailcontent += '>' + line + '\n' bodypart = MIMEText(mailcontent.encode('utf-8'), 'plain', 'UTF-8') reply.attach(bodypart) else: # attach original mode # create empty text msg bodypart = MIMEText('', 'plain', 'UTF-8') reply.attach(bodypart) # attach original msg reply.attach(mail) # copy subject subject = mail.get('Subject', '') subject = 'Fwd: ' + subject reply['Subject'] = Header(subject.encode('utf-8'), 'UTF-8').encode() # set From my_addresses = ui.accountman.get_addresses() matched_address = '' in_to = [a for a in my_addresses if a in mail.get('To', '')] if in_to: matched_address = in_to[0] else: cc = mail.get('Cc', '') + mail.get('Bcc', '') in_cc = [a for a in my_addresses if a in cc] if in_cc: matched_address = in_cc[0] if matched_address: account = ui.accountman.get_account_by_address(matched_address) fromstring = '%s <%s>' % (account.realname, account.address) reply['From'] = encode_header('From', fromstring) ui.apply_command(ComposeCommand(mail=reply))
def MIME_mail_build(source_name, source_mail, receiver_name, receiver_mail, title, txt_body): # Override python's weird assumption that utf-8 text should be encoded with # base64, and instead use quoted-printable (for both subject and body). I # can't figure out a way to specify QP (quoted-printable) instead of base64 in # a way that doesn't modify global state. :-( Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') # This example is of an email with text and html alternatives. multipart = MIMEMultipart('alternative') # We need to use Header objects here instead of just assigning the strings in # order to get our headers properly encoded (with QP). # You may want to avoid this if your headers are already ASCII, just so people # can read the raw message without getting a headache. multipart['Subject'] = Header(title.encode('utf-8'), 'UTF-8').encode() multipart['Date'] = rfc822_date() multipart['To'] = Header(receiver_name.encode('utf-8'), 'UTF-8').encode() + \ " <" + receiver_mail + ">" multipart['From'] = Header(source_name.encode('utf-8'), 'UTF-8').encode() + \ " <" + source_mail + ">" multipart['X-Mailer'] = "fnord" # Attach the parts with the given encodings. # html = '<html>...</html>' # htmlpart = MIMEText(html.encode('utf-8'), 'html', 'UTF-8') # multipart.attach(htmlpart) textpart = MIMEText(txt_body.encode('utf-8'), 'plain', 'UTF-8') multipart.attach(textpart) # And here we have to instantiate a Generator object to convert the multipart # object to a string (can't use multipart.as_string, because that escapes # "From" lines). try: io = StringIO.StringIO(multipart.as_string()) return io except Exception as excep: log.err("Unable to encode and email: %s" % excep) return None
def forum_post_as_email(self, forum, post): '''Convert a post to email''' topic = post.topic sre, subject = re.match(r'(Re: )?(.*)', post.subject).groups() if subject == '': if post.pid != topic.firstpost: sre = 'Re: ' subject = topic.title or 'topic %s' % topic.tid subject = (sre or '') + forum.subjectPrefix + subject if post.datetime is not None: pass zauthor,n = re.subn(r'[^-A-Za-z0-9]+','_', post.author) fromm = _subst(self.fromPattern, u=zauthor) msgid = _subst(self.messageIdPattern, p=post.pid) hbody = '<html><body>%s</body></html>' % post.body.encode('utf-8') try: from email.Message import Message from email.Header import Header from email.Utils import formatdate # Force quoted-printable for utf-8 instead of base64 (for Thunderbird "View source") import email.Charset as cs cs.add_charset('utf-8', cs.SHORTEST, cs.QP, 'utf-8') except ImportError: from email.message import Message from email.header import Header from email.utils import formatdate msg = Message() msg.add_header('From', fromm) msg.add_header('To', forum.recipient) hsubj = Header(subject) msg.add_header('Subject', str(hsubj)) msg.add_header('Message-ID', '<%s>' % msgid) if topic.firstpost: firstid = _subst(self.messageIdPattern, p=topic.firstpost) msg.add_header('In-Reply-To', '<%s>' % firstid) msg.add_header('References', '<%s>' % firstid) if post.datetime is not None: date = formatdate(post.datetime) msg.add_header('Date', date) msg.set_payload(hbody) msg.set_type('text/html') msg.set_charset('utf-8') return msg.as_string()
def __init__(self, sender='', recipients=[], subject='', from_defs=0, alternative=0, reply_to=None): from email.mime.multipart import MIMEMultipart from email import Charset Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') if isinstance(recipients, basestring): recipients = recipients.replace(';', ',') recipients = recipients.split(',') self.from_defs = from_defs self.sender = sender self.reply_to = reply_to or sender self.recipients = recipients self.subject = subject self.msg_root = MIMEMultipart('mixed') self.msg_multipart = MIMEMultipart('alternative') self.msg_root.attach(self.msg_multipart) self.cc = []
def enviar(self, destino, asunto, mensaje): smtpserver = smtplib.SMTP(self.smtp, self.puerto) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo smtpserver.login(self.user, self.passwd) """header = 'To:' + destino + '\n' + 'From: ' + self.user + '\n' + 'Subject:'+asunto+' \n' msg = header + '\n'+mensaje+'\n\n'""" Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') msg = MIMEMultipart('alternative') msg['To'] = destino msg['From'] = self.user msg['Subject'] = asunto part2 = MIMEText(mensaje.encode('utf-8'), 'html') msg.attach(part2) smtpserver.sendmail(self.user, destino, msg.as_string()) smtpserver.quit() """
def handle_noargs(self, **options): subject = 'hi krista' fromName = 'krista' fromAddress = '*****@*****.**' toAddressesStr = '*****@*****.**' textBody = 'hihihi' htmlBody = 'body yo yo yo' Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = "" + str(fromName) + " <" + fromAddress + ">" msg['To'] = toAddressesStr connection = SESConnection(aws_access_key_id=settings.AWS_ACCESS_KEY, aws_secret_access_key=settings.AWS_SECRET_KEY) connection.send_email(fromName + " <" + fromAddress + ">", subject, body=htmlBody, to_addresses=toAddressesStr, text_body=textBody, format="html", return_path=fromAddress)
def __init__(self, ref, old_sha1, new_sha1, push_user): "Create a Repository object" # Save configuration self.ref = ref self.old_sha1 = old_sha1 self.new_sha1 = new_sha1 self.push_user = push_user self.commits = OrderedDict() # Find our configuration directory.... if os.getenv('REPO_MGMT'): self.management_directory = os.getenv('REPO_MGMT') else: self.management_directory = os.getenv('HOME') + "/" + Repository.RepoManagementName # Set path and id.... path_match = re.match("^"+Repository.BaseDir+"(.+).git$", os.getcwd()) self.path = path_match.group(1) self.uid = self.__get_repo_id() self.__write_metadata() # Determine types.... self.repo_type = self.__get_repo_type() self.ref_type = self.__get_ref_type() self.change_type = self.__get_change_type() ref_name_match = re.match("^refs/(.+?)/(.+)$", self.ref) self.ref_name = ref_name_match.group(2) # Determine commit type for the top most commit if self.change_type == ChangeType.Delete: self.commit_type = "commit" else: command = ["git", "cat-file", "-t", self.new_sha1] process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE) self.commit_type = process.stdout.readline().strip() # Final initialisation self.__build_commits() # Ensure emails get done using the charset encoding method we want, not what Python thinks is best.... Charset.add_charset("utf-8", Charset.QP, Charset.QP)
def __init__(self, sender="", recipients=[], subject="", from_defs=0, alternative=0, reply_to=None): from email.mime.multipart import MIMEMultipart from email import Charset Charset.add_charset("utf-8", Charset.QP, Charset.QP, "utf-8") if type(recipients) == str: recipients = recipients.replace(";", ",") recipients = recipients.split(",") self.from_defs = from_defs self.sender = sender self.reply_to = reply_to or sender self.recipients = recipients self.subject = subject self.msg_root = MIMEMultipart("mixed") self.msg_multipart = MIMEMultipart("alternative") self.msg_root.attach(self.msg_multipart) self.cc = []
def enviar(self,destino,asunto,mensaje): smtpserver = smtplib.SMTP(self.smtp,self.puerto) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo smtpserver.login(self.user, self.passwd) """header = 'To:' + destino + '\n' + 'From: ' + self.user + '\n' + 'Subject:'+asunto+' \n' msg = header + '\n'+mensaje+'\n\n'""" Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') msg = MIMEMultipart('alternative') msg['To'] = destino msg['From'] = self.user msg['Subject'] = asunto part2 = MIMEText(mensaje.encode('utf-8'), 'html') msg.attach(part2) smtpserver.sendmail(self.user, destino, msg.as_string()) smtpserver.quit() """
def send_mail(sender, recipient, subject, body): # Default encoding mode set to Quoted Printable. Acts globally! Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') msg = MIMEMultipart() msg['Subject'] = "%s" % Header(subject, 'utf-8') # Only descriptive part of recipient and sender shall be encoded, # not the email address msg['From'] = "\"%s\" <%s>" % (Header(sender[0], 'utf-8'), sender[1]) msg['To'] = "\"%s\" <%s>" % (Header(recipient[0], 'utf-8'), recipient[1]) msg.attach(MIMEText(body, 'plain', 'UTF-8')) str_io = StringIO() g = Generator(str_io, False) g.flatten(msg) try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail('', recipient[1], str_io.getvalue()) except smtplib.SMTPException, e: print e
def __init__(self, sender='', recipients=[], subject='', alternative=0, reply_to=None): from email.mime.multipart import MIMEMultipart from email import Charset Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') if isinstance(recipients, basestring): recipients = recipients.replace(';', ',').replace('\n', '') recipients = recipients.split(',') # remove null recipients = filter(None, (r.strip() for r in recipients)) self.sender = sender self.reply_to = reply_to or sender self.recipients = recipients self.subject = subject self.msg_root = MIMEMultipart('mixed') self.msg_multipart = MIMEMultipart('alternative') self.msg_root.attach(self.msg_multipart) self.cc = [] self.html_set = False
def make_me_msg(me, you, subject, preamble, postamble, text_size, attachments): Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = me msg['To'] = you text = preamble + "\n\n" + give_me_text(text_size, "", "\n\n") + postamble html = "<html><head></head><body><p>%s</p></body></html>" % text.replace("\n\n", "</p><p>") msg.attach(MIMEText(text, 'plain','utf-8')) msg.attach(MIMEText(html, 'html', 'utf-8')) for attachment in attachments: filepath, type, params = attachment fp = open(filepath, 'rb') if type == "image": i = MIMEImage(fp.read()); for key,value in params.items(): i.add_header(key,value) msg.attach(i) fp.close() return msg
def __init__(self, sender="", recipients=(), subject="", alternative=0, reply_to=None, cc=()): from email.mime.multipart import MIMEMultipart from email import Charset Charset.add_charset("utf-8", Charset.QP, Charset.QP, "utf-8") if isinstance(recipients, basestring): recipients = recipients.replace(";", ",").replace("\n", "") recipients = split_emails(recipients) # remove null recipients = filter(None, (strip(r) for r in recipients)) self.sender = sender self.reply_to = reply_to or sender self.recipients = recipients self.subject = subject self.msg_root = MIMEMultipart("mixed") self.msg_multipart = MIMEMultipart("alternative") self.msg_root.attach(self.msg_multipart) self.cc = cc or [] self.html_set = False
def send_activation_email(self, full_name, email, url): ''' Sends activation email via smtp protocol. :param full_name: :param email: :param url: ''' # Example address data from_address = [u'Sport Magazine', 'mail.sportmagazine.ir'] recipient = [unicode(full_name), email] subject = u'User Activation Email (Simaye Salem)' # Example body html = \ u'<b>Activation URL (Just Click)</b><br\><h1><a href="{url}">Click Here To Activate ...</a></h1>'.format(url=url) # Default encoding mode set to Quoted Printable. Acts globally! Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') msg = MIMEMultipart('alternative') msg['Subject'] = "%s" % Header(subject, 'utf-8') # Only descriptive part of recipient and sender shall be encoded, not the email address msg['From'] = "\"%s\" <%s>" % (Header(from_address[0], 'utf-8'), from_address[1]) msg['To'] = "\"%s\" <%s>" % (Header(recipient[0], 'utf-8'), recipient[1]) # Attach both parts htmlpart = MIMEText(html, 'html', 'UTF-8') msg.attach(htmlpart) smtpServer = smtplib.SMTP() smtpServer.connect() smtpServer.sendmail(from_address[1], [recipient[1]], msg.as_string()) smtpServer.quit()
def send_change_password_email(self, full_name, email, change_code): ''' Sends change password email via smtp protocol. :param full_name: :param email: :param change_code: ''' # Example address data from_address = [u'Sport Magazine', 'mail.sportmagazine.ir'] recipient = [unicode(full_name), email] subject = u'User Change Password Email (Simaye Salem)' # Example body html = \ u'<b>Change Password Code (Use this code to change password)</b><br\><h1>change_code</h1>'.format(change_code=change_code) # Default encoding mode set to Quoted Printable. Acts globally! Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') msg = MIMEMultipart('alternative') msg['Subject'] = "%s" % Header(subject, 'utf-8') # Only descriptive part of recipient and sender shall be encoded, not the email address msg['From'] = "\"%s\" <%s>" % (Header(from_address[0], 'utf-8'), from_address[1]) msg['To'] = "\"%s\" <%s>" % (Header(recipient[0], 'utf-8'), recipient[1]) # Attach both parts htmlpart = MIMEText(html, 'html', 'UTF-8') msg.attach(htmlpart) smtpServer = smtplib.SMTP() smtpServer.connect() smtpServer.sendmail(from_address[1], [recipient[1]], msg.as_string()) smtpServer.quit()
def send_message_notification(sender, instance, **kwargs): """ Send email when user receives a new message. This email contains the full text and a link to read it online. We trigger this when a MessageRecipient is saved and not when a Message is saved because umessages first saves a message and then adds its recipients, so when a Message is saved, it doesn't yet have a list of recipients. """ if not instance.user.email: # Email can be missing for users registered with Twitter # or LinkedIn return params = { 'sender': instance.message.sender.username, 'body': instance.message.body, } message_url_path = reverse('userena_umessages_detail', kwargs={'username': params['sender']}) params['message_url'] = "%s://%s%s" % ( get_protocol(), Site.objects.get_current(), message_url_path) subject = _( u'New message from %(sender)s on Imagination For People') % params message = render_to_string('umessages/message_notification.txt', params) recipient = instance.user.email # XXX Resets the Content-Transfer-Encoding in email header # Avoids bad encoding of UTF-8 body # See https://code.djangoproject.com/ticket/3472 from email import Charset Charset.add_charset('utf-8', Charset.SHORTEST, 'utf-8', 'utf-8') send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [recipient])
def post_processing(self, p_info): branch_name = p_info["basename"].replace("_", " ") # generate title HTML title_html_filename = os.path.normpath( os.path.join( DIR_OUTPUT, "%s%s_%s.html" % (p_info["basename"], ListTypes.gettypestr( ListTypes.TITLE_PAGING_LIST), p_info["timestamp"]))) try: # generate HTML file # blocking is probably okay here...maybe... p = Popen( "%s -o %s %s %s" % (XSLTPROC_CMD, title_html_filename, SQUIRE_T_2XHTML_XSL_FILE, p_info["title_list_fullpath_xml"]), shell=True) sts = os.waitpid(p.pid, 0)[1] # create symlink latest_title_link = "%s%s/latest_title.html" % (LISTS_DIR, p_info["basename"]) latest_raw_title_link = "%s%s/latest_title_raw.txt" % ( LISTS_DIR, p_info["basename"]) try: os.remove(latest_title_link) except: pass try: os.symlink(title_html_filename, latest_title_link) except: self.__logger.info(sys.exc_info()[1]) try: os.remove(latest_raw_title_link) except: pass try: os.symlink(p_info["title_list_fullpath_archive"], latest_raw_title_link) except: self.__logger.info(sys.exc_info()[1]) except: self.__logger.info(sys.exc_info()[1]) latest_item_link = "%s%s/latest_item.html" % (LISTS_DIR, p_info["basename"]) latest_raw_item_link = "%s%s/latest_item_raw.txt" % ( LISTS_DIR, p_info["basename"]) if p_info["has_item_list"]: # generate item HTML, if available item_html_filename = os.path.normpath( os.path.join( DIR_OUTPUT, "%s%s_%s.html" % (p_info["basename"], ListTypes.gettypestr( ListTypes.ITEM_PAGING_LIST), p_info["timestamp"]))) try: # generate HTML file # blocking is probably okay here...maybe... p = Popen("%s -o %s %s %s" % (XSLTPROC_CMD, item_html_filename, SQUIRE_I_2XHTML_XSL_FILE, p_info["item_list_fullpath_xml"]), shell=True) sts = os.waitpid(p.pid, 0)[1] try: os.remove(latest_item_link) os.remove(latest_raw_item_link) except: pass try: os.symlink(item_html_filename, latest_item_link) os.symlink(p_info["item_list_fullpath_archive"], latest_raw_item_link) except: self.__logger.info(sys.exc_info()[1]) except: self.__logger.info(sys.exc_info()[1]) else: try: os.remove(latest_item_link) os.remove(latest_raw_item_link) except: pass try: os.symlink(NO_ITEM_HTML_FILENAME, latest_item_link) os.symlink(NO_ITEM_RAW_FILENAME, latest_raw_item_link) except: self.__logger.info(sys.exc_info()[1]) # send email if branch_name in self.__location_emails: msg = MIMEMultipart("alternative") Charset.add_charset("utf-8", Charset.QP, Charset.QP, "utf-8") msg["Subject"] = "%s Paging Lists for %s" % (branch_name, p_info["timestamp"]) msg["From"] = SEND_EMAIL_AS msg["To"] = ", ".join(self.__location_emails[branch_name]) msg["Preamble"] = msg["Subject"] branch_url = "%s/%s/index.html" % (LISTS_URL, p_info["basename"]) # TODO: replace these with external templates body_text = "\n Please visit %s to access the %s Library paging lists.\n\nSpreadsheet versions of your paging lists are also attached to this email.\n\nIf there is a problem with your paging lists, please contact the Help Desk at %s or %s." % ( branch_url, branch_name, HELP_DESK_EMAIL, HELP_DESK_PHONE) body_html = """\ <html> <head></head> <body> <p>Please visit <a href='%s'>here</a> to access the %s Library paging lists.</p> <p>Spreadsheet versions of your paging lists are also attached to this email.</p> <p>If there is a problem with your paging lists, please contact the Help Desk at <a href='mailto:%s'>%s</a> or %s.</p> </body> </html> """ % (branch_url, branch_name, HELP_DESK_EMAIL, HELP_DESK_EMAIL, HELP_DESK_PHONE) try: # load and encode Title csv file title_csv_attachment_file = open( p_info["title_list_fullpath_csv"], "rb") title_csv_attachment = MIMEBase("text", "csv") title_csv_attachment.set_payload( title_csv_attachment_file.read()) Encoders.encode_7or8bit(title_csv_attachment) title_csv_attachment.add_header( 'Content-Disposition', 'attachment', filename=os.path.basename( p_info["title_list_fullpath_csv"])) msg.attach(title_csv_attachment) title_csv_attachment_file.close() # load and encode Title html file title_html_attachment_file = open(title_html_filename, "rb") title_html_attachment = MIMEBase('application', 'octet-stream') title_html_attachment.set_payload( title_html_attachment_file.read()) Encoders.encode_base64(title_html_attachment) title_html_attachment.add_header( 'Content-Disposition', 'attachment', filename=os.path.basename(title_html_filename)) msg.attach(title_html_attachment) title_html_attachment_file.close() except: self.__logger.info(sys.exc_info()[1]) # add Item attachements, if available if p_info["has_item_list"]: try: # load and encode Item csv file item_csv_attachment_file = open( p_info["item_list_fullpath_csv"], "rb") item_csv_attachment = MIMEBase("text", "csv") item_csv_attachment.set_payload( item_csv_attachment_file.read()) Encoders.encode_7or8bit(item_csv_attachment) item_csv_attachment.add_header( 'Content-Disposition', 'attachment', filename=os.path.basename( p_info["item_list_fullpath_csv"])) msg.attach(item_csv_attachment) item_csv_attachment_file.close() # load and encode Item html file item_html_attachment_file = open(item_html_filename, "rb") item_html_attachment = MIMEBase('application', 'octet-stream') item_html_attachment.set_payload( item_html_attachment_file.read()) Encoders.encode_base64(item_html_attachment) item_html_attachment.add_header( 'Content-Disposition', 'attachment', filename=os.path.basename(item_html_filename)) msg.attach(item_html_attachment) item_html_attachment_file.close() except: self.__logger.info(sys.exc_info()[1]) # attach body msg.attach(MIMEText(body_text, "plain")) msg.attach(MIMEText(body_html, "html")) # send mail s = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) s.sendmail(SEND_EMAIL_AS, self.__location_emails[branch_name], msg.as_string()) s.quit() self.__logger.info("%s paging list emailed to %s" % (branch_name, msg["To"]))
import glob import random import time import base64 # fix for python2 to 3 compatibility try: from cStringIO import StringIO except NameError: from io import StringIO from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.header import Header from email.generator import Generator from email import Charset from email import Encoders Charset.add_charset('utf-8', Charset.BASE64, Charset.BASE64, 'utf-8') # default the email messages to plain text # unless otherwise specified message_flag = "plain" # impor the core modules from src.core.setcore import * # do we want to track the users that click links track_email = check_config("TRACK_EMAIL_ADDRESSES=").lower() definepath = os.getcwd() # DEFINE SENDMAIL CONFIG and WEB ATTACK sendmail = 0
def cmd_bar(self, _chan, _args, sender_nick): "envoie un email aux grelakins" # vérification que l'invocateur soit un grelakins if hashlib.sha224(sender_nick).hexdigest() in self.liste_grelakins: # vérification que c'est la première invocation du messager if self.date_bar != str(time.strftime('%d/%m/%y', time.localtime())): heure = _args[0].decode('utf-8') lieu = ' '.join(_args[1:]).decode('utf-8') lieu = lieu.lower().strip().replace(" ", "") if re.match(r"(1[6-9]|2[0-4])+([hH]$|([hH]+" + "[0-5][0-9])|[:]+[0-5][0-9]+)", heure): # test de la compatibilité du format de l'heure # REGLE: on va au bar entre 16h et 24h59, # après c'est fermé, avant c'est être alcoolique for cle, valeur in self.liste_bar.items(): if lieu in valeur: # teste si le bar proposé est cool from_address = [u"Honorable tofbot", os.getenv( "TOFBOT_MAIL", "")] pwd = "" recipient = [u"Michels", os.getenv( "TOFBOT_MAILINGLIST", "")] subject = u"Bar ce soir" content = u"""Bonsoir les jeunes, Aujourd'hui, certains Michels vont au bar %s à %s. Rejoignez les! Tofbot, au service de %s """ % (cle, heure, sender_nick) content = content.encode('utf-8') Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') msg = MIMEMultipart('alternative') msg['Subject'] = "%s" % Header(subject, 'utf-8') msg['From'] = "\"%s\" <%s>" % (Header( from_address[0], 'utf-8'), from_address[1]) msg['To'] = "\"%s\" <%s>" % ( Header(recipient[0], 'utf-8'), recipient[1]) txtpart = MIMEText(content, 'plain', 'UTF-8') msg.attach(txtpart) str_out = StringIO() g = Generator(str_out, False) g.flatten(msg) mail_server = "localhost" server = smtplib.SMTP(mail_server, 25) server.ehlo() server.sendmail(from_address[1], recipient[1], str_out.getvalue()) server.quit() # message de confirmation de l'envoi de l'email self.say(u"Michels avertis!") self.date_bar = str(time.strftime( '%d/%m/%y', time.localtime())) return # avertissement bar non autorisé self.say(u"J'envoie pas ce mail, ce bar n'est pas cool!") else: # avertissement mauvaise heure if re.match(r"^(0[0-9]|1[0-5])", heure): # cas de l'heure trop matinale pour un Michel self.say(u"Beaucoup trop tôt, mec!") else: # cas d'un format horaire faux self.say(u"Euh... L'heure n'est pas claire.") else: self.say(u"Rameutage au bar déjà invoqué aujourd'hui") else: self.say(u"Seul un Grelakins autorisé peut envoyer un mail !bar")