def send_info_mail(solver_binary): num_total = 0 num_successful = 0 num_crash = 0 for solver_config in solver_binary.solver_configurations: qry = db.session.query( db.ExperimentResult).filter_by(solver_configuration=solver_config) num_total += qry.count() num_successful += qry.filter( db.ExperimentResult.resultCode.like(u"1%")).count() num_crash += qry.filter( db.ExperimentResult.status.in_(constants.STATUS_ERRORS)).count() user = solver_binary.solver.user msg = MIMEText(( 'Dear ' + user.firstname + " " + user.lastname + ',\n\n' + 'This is an automatically generated e-mail regarding your solver submission to the SAT Challenge 2012.\n' + 'Your solver was executed in our execution environment with the following results:\n' + str(num_total - num_crash) + " out of " + str(num_total) + " runs finished without crashing\n" + str(num_successful) + " out of " + str(num_total) + " runs produced a correct result within the given time\n\n" + 'Please have a look at ' + base_url + 'experiments/ for detailed information about the test\n' ).encode('utf8'), 'plain', 'utf8') msg['Subject'] = '[SAT Challenge 2012] Solver tested' msg.set_charset('utf8') send_mail(msg, solver_binary.solver.user.email)
def sendEmail(htmlText): msgRoot = MIMEMultipart('related') msgRoot['Subject'] = 'testtttttttttttt' msgRoot['From'] = user msgRoot['To'] = user msgRoot.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText(htmlText, 'html', 'utf-8') msgText.set_charset("utf-8") msgAlternative.attach(msgText) smtp =smtplib.SMTP('smtp.gmail.com', port=587, timeout=20) smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(user, passwd) smtp.sendmail(user, user, msgRoot.as_string()) sleep(5) smtp.quit() return
def send_html_email_no_encode(self, smtp, send_from, send_pass, send_tos, plain_txt, html_content, title ): ''' ''' now = datetime.datetime.now() today = datetime.date.today() msg = MIMEMultipart() body = MIMEMultipart('alternative') msg['Subject'] = Header(title, "utf-8") msg['From'] = send_from text = plain_txt html = html_content part_text = MIMEText(text, 'plain', 'utf-8') body.attach(part_text) try: part_html = MIMEText(html, 'html', 'utf-8') part_html.set_charset('utf-8') body.attach(part_html) except: print 'error html format' msg.attach(body) try: smtp_server = smtplib.SMTP() smtp_server.connect(smtp) smtp_server.login(send_from, send_pass) smtp_server.sendmail(send_from, send_tos, msg.as_string()) smtp_server.close() except Exception, e: print "send error:", e
def mejl(tabelka, ustawieniaMejla): od, do, smtp = tuple([ustawieniaMejla[x] for x in ["od", "do", "smtp"]]) tekst = u"<h2>Wyniki</h2>" + "<ul>" for dzien in tabelka.keys(): tekst = tekst + "<li>" + uni(dzien) + "<ol>" for wynikDnia in tabelka[dzien]: tekst = tekst + "<li>" + uni(wynikDnia) + "</li>" tekst = tekst + "</ol></li>" tekst = tekst + ("</ul>" + "<br/>\r-- " + "<br/>\r %s") % datetime.datetime.now().__str__() temat = "[MEDICOVER] %s" % (datetime.datetime.now()) charset = Charset("utf-8") tresc = MIMEText(tekst.encode("utf-8"), "html") tresc.set_charset(charset) tresc["From"] = od tresc["To"] = ", ".join(do) tresc["Subject"] = temat if ustawieniaMejla.get("smtp_tls"): smtp_pass = haslo(smtp, od, ustawieniaMejla.get("smtp_password")) serwer = smtplib.SMTP(smtp, 587) serwer.starttls() serwer.login(od, smtp_pass) else: serwer = smtplib.SMTP(smtp) serwer.sendmail(od, do, tresc.as_string()) serwer.quit()
def send_html_email_no_encode(self, smtp, send_from, send_pass, send_tos, plain_txt, html_content, title): ''' ''' now = datetime.datetime.now() today = datetime.date.today() msg = MIMEMultipart() body = MIMEMultipart('alternative') msg['Subject'] = Header(title, "utf-8") msg['From'] = send_from text = plain_txt html = html_content part_text = MIMEText(text, 'plain', 'utf-8') body.attach(part_text) try: part_html = MIMEText(html, 'html', 'utf-8') part_html.set_charset('utf-8') body.attach(part_html) except: print 'error html format' msg.attach(body) try: smtp_server = smtplib.SMTP() smtp_server.connect(smtp) smtp_server.login(send_from, send_pass) smtp_server.sendmail(send_from, send_tos, msg.as_string()) smtp_server.close() except Exception, e: print "send error:", e
def sendMail(self, to_list, sub, content): me = "Admin <admin@" + self.mail_postfix + ">" msg = MIMEMultipart() msg["Accept-Charset"]="ISO-8859-1,utf-8" msg['Subject'] = sub msg['From'] = me msg['To'] = to_list txt=MIMEText(content, 'html') txt.set_charset("utf-8") msg.attach(txt) if self.attachment_path !="": msg.attach(self.attach()) try: s = smtplib.SMTP_SSL() s.connect(self.mail_host, self.mail_port) s.login(self.mail_user, self.mail_pass) s.sendmail(me, to_list, msg.as_string()) s.close() print '发送成功!' return True except Exception, e: print '发送失败!' print str(e)
def sendFirstMail(self, proprioPk, majDate): proprio = self.getProprio(proprioPk) proprioMail = proprio.pro_email if not proprioMail: print 'WARNING : %s %s has no email' % (proprio.pro_prenom1, proprio.pro_nom1) return mailFrom = "*****@*****.**" subject = "Votre calendrier sur le site des Gîtes de Wallonie" key = self.insertProprioHash(proprio) linkUrl = "https://www.gitesdewallonie.be/reactivation-calendrier?key=%s" % key mail = MIMEText((FIRST_MAIL % linkUrl).encode('utf-8')) mail['From'] = mailFrom mail['Subject'] = subject mail['To'] = proprioMail mail.set_charset('utf-8') server = smtplib.SMTP('localhost') server.sendmail(mailFrom, [proprioMail], mail.as_string()) server.quit() print 'Sending warning mail to %s %s (%s) - last modification date : %s - key : %s' % \ (proprio.pro_prenom1, proprio.pro_nom1, proprioMail, majDate.strftime('%d-%m-%Y'), key)
def send_reminder_email(content, to, subject): to = ['*****@*****.**', '*****@*****.**'] text_subtype = 'plain' try: msg = MIMEText(content.encode('utf-8'), text_subtype) msg.set_charset('utf-8') msg['Subject'] = subject msg['From'] = smtp_conf['from'] msg['To'] = ','.join(to) msg['Reply-To'] = smtp_conf['reply-to'] conn = SMTP(smtp_conf['server'], 465) conn.set_debuglevel(False) conn.login(smtp_conf['user'], smtp_conf['pass']) try: conn.sendmail(smtp_conf['from'], to, msg.as_string()) finally: conn.close() except Exception, exc: sys.exit( "mail failed; %s" % str(exc) ) # give a error message
def createMessage(fro, to, subject, text, files=None): if files is None: files=[] assert type(to) == list assert type(files) == list #fro = FROM msg = MIMEMultipart() msg['From'] = fro msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject text_message = MIMEText(text) text_message.set_charset('UTF-8') msg.attach(text_message) 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) return msg
def mejl(tabelka, ustawieniaMejla): od, do, smtp = tuple([ustawieniaMejla[x] for x in ["od", "do", "smtp"]]) tekst = u"<h2>Wyniki</h2>" + "<ul>" for dzien in tabelka.keys(): tekst = tekst + "<li>" + uni(dzien) + "<ol>" for wynikDnia in tabelka[dzien]: tekst = tekst + "<li>" + uni(wynikDnia) + "</li>" tekst = tekst + "</ol></li>" tekst = tekst + ("</ul>" +"<br/>\r-- " +"<br/>\r %s") \ % datetime.datetime.now().__str__() temat = "[MEDICOVER] %s" % (datetime.datetime.now()) charset = Charset('utf-8') tresc = MIMEText(tekst.encode('utf-8'), 'html') tresc.set_charset(charset) tresc['From'] = od tresc['To'] = ", ".join(do) tresc['Subject'] = temat if ustawieniaMejla.get('smtp_tls'): smtp_pass = haslo(smtp, od, ustawieniaMejla.get('smtp_password')) serwer = smtplib.SMTP(smtp, 587) serwer.starttls() serwer.login(od, smtp_pass) else: serwer = smtplib.SMTP(smtp) serwer.sendmail(od, do, tresc.as_string()) serwer.quit()
def sendMail(self, to_list, sub, content): me = "Admin <admin@" + self.mail_postfix + ">" msg = MIMEMultipart() msg["Accept-Charset"] = "ISO-8859-1,utf-8" msg['Subject'] = sub msg['From'] = me msg['To'] = to_list txt = MIMEText(content, 'html') txt.set_charset("utf-8") msg.attach(txt) if self.attachment_path != "": msg.attach(self.attach()) try: s = smtplib.SMTP_SSL() s.connect(self.mail_host, self.mail_port) s.login(self.mail_user, self.mail_pass) s.sendmail(me, to_list, msg.as_string()) s.close() print '发送成功!' return True except Exception, e: print '发送失败!' print str(e)
def send_mail(send_from, send_to, subject, text, files=[], server="localhost", ssl=False, username=None, password=None): msg = MIMEMultipart('alternative') msg.set_charset('utf-8') msg['From'] = send_from msg['To'] = send_to msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject part = MIMEText(text) part.set_charset('utf-8') msg.attach(part) if ssl: smtp = smtplib.SMTP_SSL(server) else: smtp = smtplib.SMTP(server) if username: smtp.login(username, password) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def _send_alert(self, loglevel, subject, body, **kwargs): c = self.config self.connect() data = dict() data['level'] = loglevel.upper() data['service'] = c.get('service') data['subject'] = subject mail_receivers = c['receivers'] mail_from = '%s <%s>' % (c['sender'], c['user']) if 'sender' in c else c['user'] mail_subject = self.subject_format % data mail_body = body message = MIMEText(mail_body, 'plain') message['From'] = mail_from message['Subject'] = mail_subject message.set_charset('utf-8') result = self.conn.sendmail(mail_from, mail_receivers, message.as_string()) if not c['keep_alive']: self.quit() return True if len(result) == 0 else False
def to_MIMEText(self): def utf8(s, reject_newlines=True): if reject_newlines and '\n' in s: raise HeaderParseError( 'header value contains unexpected newline: {!r}'.format(s)) return s.encode('utf8') if isinstance(s, unicode) else s fr = '"%s" <%s>' % ( self.from_name().replace('"', ''), self.fr_addr.replace('>', ''), ) # Addresses that start with a dash could confuse poorly-written # software's argument parsers, and thus are disallowed by default in # Postfix: http://www.postfix.org/postconf.5.html#allow_min_user if not fr.startswith('-') and not self.to_addr.startswith('-'): msg = MIMEText(utf8(self.body, reject_newlines=False)) msg.set_charset('utf8') msg['To'] = utf8(self.to_addr) msg['From'] = utf8(fr) msg['Subject'] = utf8(self.subject) if self.user: msg['X-Reddit-username'] = utf8(self.user.name) msg['X-Reddit-ID'] = self.msg_hash if self.reply_to: msg['Reply-To'] = utf8(self.reply_to) return msg return None
def to_MIMEText(self): def utf8(s, reject_newlines=True): if reject_newlines and '\n' in s: raise HeaderParseError( 'header value contains unexpected newline: {!r}'.format(s)) return s.encode('utf8') if isinstance(s, unicode) else s fr = '"%s" <%s>' % ( self.from_name().replace('"', ''), self.fr_addr.replace('>', ''), ) if not fr.startswith('-') and not self.to_addr.startswith('-'): # security msg = MIMEText(utf8(self.body, reject_newlines=False)) msg.set_charset('utf8') msg['To'] = utf8(self.to_addr) msg['From'] = utf8(fr) msg['Subject'] = utf8(self.subject) if self.user: msg['X-Reddit-username'] = utf8(self.user.name) msg['X-Reddit-ID'] = self.msg_hash if self.reply_to: msg['Reply-To'] = utf8(self.reply_to) return msg return None
def to_MIMEText(self): def utf8(s, reject_newlines=True): if reject_newlines and '\n' in s: raise HeaderParseError( 'header value contains unexpected newline: {!r}'.format(s)) return s.encode('utf8') if isinstance(s, unicode) else s fr = '"%s" <%s>' % ( self.from_name().replace('"', ''), self.fr_addr.replace('>', ''), ) # Addresses that start with a dash could confuse poorly-written # software's argument parsers, and thus are disallowed by default in # Postfix: http://www.postfix.org/postconf.5.html#allow_min_user if not fr.startswith('-') and not self.to_addr.startswith('-'): msg = MIMEText(utf8(self.body, reject_newlines=False)) msg.set_charset('utf8') msg['To'] = utf8(self.to_addr) msg['From'] = utf8(fr) msg['Subject'] = utf8(self.subject) timestamp = time.mktime(self.date.timetuple()) msg['Date'] = utf8(email.utils.formatdate(timestamp)) if self.user: msg['X-Reddit-username'] = utf8(self.user.name) msg['X-Reddit-ID'] = self.msg_hash if self.reply_to: msg['Reply-To'] = utf8(self.reply_to) return msg return None
def to_MIMEText(self): def utf8(s, reject_newlines=True): if reject_newlines and "\n" in s: raise HeaderParseError("header value contains unexpected newline: {!r}".format(s)) return s.encode("utf8") if isinstance(s, unicode) else s fr = '"%s" <%s>' % (self.from_name().replace('"', ""), self.fr_addr.replace(">", "")) # Addresses that start with a dash could confuse poorly-written # software's argument parsers, and thus are disallowed by default in # Postfix: http://www.postfix.org/postconf.5.html#allow_min_user if not fr.startswith("-") and not self.to_addr.startswith("-"): msg = MIMEText(utf8(self.body, reject_newlines=False)) msg.set_charset("utf8") msg["To"] = utf8(self.to_addr) msg["From"] = utf8(fr) msg["Subject"] = utf8(self.subject) timestamp = time.mktime(self.date.timetuple()) msg["Date"] = utf8(email.utils.formatdate(timestamp)) if self.user: msg["X-Reddit-username"] = utf8(self.user.name) msg["X-Reddit-ID"] = self.msg_hash if self.reply_to: msg["Reply-To"] = utf8(self.reply_to) return msg return None
def to_MIMEText(self): def utf8(s, reject_newlines=True): if reject_newlines and '\n' in s: raise HeaderParseError( 'header value contains unexpected newline: {!r}'.format(s)) return s.encode('utf8') if isinstance(s, unicode) else s fr = '"%s" <%s>' % ( self.from_name().replace('"', ''), self.fr_addr.replace('>', ''), ) if not fr.startswith('-') and not self.to_addr.startswith( '-'): # security msg = MIMEText(utf8(self.body, reject_newlines=False)) msg.set_charset('utf8') msg['To'] = utf8(self.to_addr) msg['From'] = utf8(fr) msg['Subject'] = utf8(self.subject) if self.user: msg['X-Reddit-username'] = utf8(self.user.name) msg['X-Reddit-ID'] = self.msg_hash if self.reply_to: msg['Reply-To'] = utf8(self.reply_to) return msg return None
def create_message(from_addr, to_addr, subject, body): msg = MIMEText(body.encode("utf-8")) msg.set_charset("utf-8") msg["Subject"] = subject msg["From"] = from_addr msg["To"] = to_addr msg["Date"] = formatdate() return msg
def __prepareEmail(self, conn, mailid, mailtype, header, data, attlen): """ Method creates text part of email, it means without base64 encoded attachments. This includes following steps: 1) Create HDF dataset (base of templating) 2) Template subject 3) Run templating for all wanted templates and attach them 4) Create email headers 5) Dump email in string form """ # init headers hdf = neo_util.HDF() # pour defaults in data set for pair in self.__dbGetDefaults(conn): hdf.setValue("defaults." + pair[0], pair[1]) # pour user provided values in data set for pair in data: hdf.setValue(pair.key, pair.value) mailtype_id, subject_tpl, templates = self.__dbGetMailTypeData(conn, mailtype) # render subject cs = neo_cs.CS(hdf) cs.parseStr(subject_tpl) subject = cs.render() # Create email object multi or single part (we have to decide now) if attlen > 0 or len(templates) > 1 or self.vcard: msg = MIMEMultipart() # render text attachments for item in templates: cs = neo_cs.CS(hdf) cs.parseStr(item["template"]) mimetext = MIMEText(cs.render().strip() + '\n', item["type"]) mimetext.set_charset("utf-8") # Leave this commented out, otherwise it duplicates header # Content-Transfer-Encoding #Encoders.encode_7or8bit(mimetext) msg.attach(mimetext) # Attach vcard attachment if configured so if self.vcard: mimetext = MIMEText(self.vcard, "x-vcard") mimetext.set_charset("utf-8") msg.attach(mimetext) else: # render text attachment cs = neo_cs.CS(hdf) cs.parseStr(templates[0]["template"]) msg = MIMEText(cs.render().strip()+'\n', templates[0]["type"]) msg.set_charset("utf-8") # init email header (BEWARE that header struct is modified in this # call to function, so it is filled with defaults for not provided # headers, which is important for obtaining envelope sender). self.__dbSetHeaders(conn, mailid, subject, header, msg) return msg.as_string(), mailtype_id
def sendEmail(mailserver, fromAddr, toAddrList, subject, content): print 'sending email...' #msg = MIMEText(content, _charset='utf-8') msg = MIMEText(content) msg.set_charset('utf-8') msg['Subject'] = subject msg['From'] = fromAddr msg['To'] = toAddrList[0] mailserver.sendmail(fromAddr, toAddrList, msg.as_string())
def sendmail(self, to, subject, txt, attach=None): self.msg["Accept-Language"] = "zh_CN" self.msg["Accept-Charset"] = "ISO-8859-1,utf-8" txt = MIMEText(txt) txt.set_charset("utf-8") self.msg["To"] = to self.msg["Subject"] = subject self.msg.attach(txt) self.smtp.sendmail(self.msg["From"], self.msg["To"], self.msg.as_string())
def simple_email(to, fr, subj, body): def utf8(s): return s.encode('utf8') if isinstance(s, unicode) else s msg = MIMEText(utf8(body)) msg.set_charset('utf8') msg['To'] = utf8(to) msg['From'] = utf8(fr) msg['Subject'] = utf8(subj) send_mail(msg, fr, to)
def send_mail(sender, recipients, subject, template, params, cc=None, cc_admin=False, context=None, admin_alternative_email=None): if 'NO_MAIL' in os.environ: return if not cc: cc = [] footer_text = pkg_resources.resource_string('pcp.contenttypes.templates', 'footer.txt') params['footer'] = unicode(footer_text, 'utf-8') formatter = Formatter() email_text = pkg_resources.resource_string('pcp.contenttypes.templates', template) try: email_text = unicode(email_text, 'utf-8') except UnicodeError: email_text = unicode(email_text, 'iso-8859-15') email_text = formatter.format(email_text, **params) msg = MIMEText(email_text.encode('utf-8'), _charset='utf8') msg.set_charset('utf-8') recipients = [r for r in recipients if r] msg['To'] = ','.join(recipients) if sender: msg['From'] = sender else: portal = plone.api.portal.get() msg['From'] = formataddr( (portal.email_from_name, portal.email_from_address)) if cc_admin: if admin_alternative_email: cc.append(admin_alternative_email) else: cc.append(portal.email_from_address) if cc: msg['CC'] = ','.join(cc) msg['Subject'] = subject if context: PersistentLoggerAdapter(context).log( u'Mail "{}" to {} + {}, Subject: "{}" sent'.format( subject, recipients, cc, subject)) mh = plone.api.portal.get_tool('MailHost') mh.send(msg.as_string(), immediate=True)
def as_msg(self): msg = MIMEText(utf8(self.body), self.subtype) msg.set_charset('utf-8') msg['To'] = utf8(self.email) msg['Subject'] = utf8(self.subject) if self.date: msg['Date'] = self.date else: msg['Date'] = formatedate() return msg
class Message(object): def __init__(self, from_addr, to_addrs, subject, message, mime="text/plain", charset="utf-8"): self.subject = subject self.from_addr = from_addr self.to_addrs = isinstance(to_addrs, types.StringType) and [to_addrs] or to_addrs self.msg = None self.__cache = None self.message = MIMEText(message) self.message.set_charset(charset) self.message.set_type(mime) def attach(self, filename, mime=None, charset=None, content=None): base = os.path.basename(filename) if content is None: fd = open(filename) content = fd.read() fd.close() if not isinstance(content, types.StringType): raise TypeError("don't know how to handle content: %s" % type(content)) part = MIMEBase("application", "octet-stream") part.set_payload(content) Encoders.encode_base64(part) part.add_header("Content-Disposition", "attachment; filename=\"%s\"" % base) if mime is not None: part.set_type(mime) if charset is not None: part.set_charset(charset) if self.msg is None: self.msg = MIMEMultipart() self.msg.attach(self.message) self.msg.attach(part) def __str__(self): return self.__cache or "nuswit mail message: not rendered yet" def render(self): if self.msg is None: self.msg = self.message self.msg["Subject"] = self.subject self.msg["From"] = self.from_addr self.msg["To"] = COMMASPACE.join(self.to_addrs) self.msg["Date"] = formatdate(localtime=True) if self.__cache is None: self.__cache = self.msg.as_string() return StringIO(self.__cache)
def sendEmail(authInfo, fromAdd, toAdd, subject, plainText, htmlText): strFrom = fromAdd strTo = ', '.join(toAdd) server = authInfo.get('server') user = authInfo.get('user') passwd = authInfo.get('password') if not (server and user and passwd) : print 'incomplete login info, exit now' return msgRoot = MIMEMultipart('related') msgRoot["Accept-Charset"]="ISO-8859-1,utf-8" msgRoot["Accept-Language"]="zh-CN" msgRoot['Subject'] = subject msgRoot['From'] = strFrom msgRoot['To'] = strTo msgRoot.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText(plainText, 'plain', 'utf-8') msgText.set_charset("utf-8") msgAlternative.attach(msgText) msgText.set_charset("utf-8") msgText = MIMEText(htmlText, 'html', 'utf-8') msgAlternative.attach(msgText) fp = open('test.jpg', 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<image1>') msgRoot.attach(msgImage) print msgRoot.as_string() """ smtp =smtplib.SMTP(server, port=587, timeout=20) smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(user, passwd) smtp.sendmail(strFrom, strTo, msgRoot.as_string()) sleep(5) smtp.quit() """ return
def send_mail(send_from, send_to, subject, text, files=[], server="localhost"): msg = MIMEMultipart('alternative') msg.set_charset('utf-8') msg['From'] = send_from msg['To'] = send_to msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject part = MIMEText(text) part.set_charset('utf-8') msg.attach(part) smtp = smtplib.SMTP(server) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def email_html_send_attach(email_from, email_to, subject, body, email_cc=None, email_bcc=None, on_error=False, reply_to=False, attach=None, tinycrm=False): if not email_cc: email_cc=[] if not email_bcc: email_bcc=[] if not attach: attach=[] msg = MIMEMultipart('related') msg['Subject'] = Header(subject.decode('utf8'), 'utf-8') msg['From'] = email_from del msg['Reply-To'] if reply_to: msg['Reply-To'] = reply_to msg['To'] = COMMASPACE.join(email_to) if email_cc: msg['Cc'] = COMMASPACE.join(email_cc) if email_bcc: msg['Bcc'] = COMMASPACE.join(email_bcc) if tinycrm: msg['Message-Id'] = '<'+str(time.time())+'-tinycrm-'+str(tinycrm)+'@'+socket.gethostname()+'>' msg['Date'] = formatdate(localtime=True) msg_alt = MIMEMultipart('alternative') msg_alt.attach(MIMEText("Vous devez activez l'affichage en mode HTML pour lire ce message.")) body_part = MIMEText(body , _subtype='html') body_part.set_charset('UTF-8') msg_alt.attach(body_part) msg.attach(msg_alt) for (fname,fcontent) in attach: part = MIMEBase('application', "octet-stream") part.set_payload( fcontent ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % (fname,)) msg.attach(part) try: s = smtplib.SMTP() s.connect(config['smtp_server']) if config['smtp_user'] or config['smtp_password']: s.login(config['smtp_user'], config['smtp_password']) s.sendmail(email_from, email_to + email_cc + email_bcc, msg.as_string()) s.quit() except Exception, e: import logging logging.getLogger().info(str(e))
def send_total_email(email, data): time_stamp = strftime('%Y-%m-%d %H:%M', localtime()) header = ''' <html> <head> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"/> <style> table{border:1px solid #ddd;border-collapse:collapse; } table td, table th {padding:8px;word-wrap:break-word;} </style> </head> <body> <table border="3" width=750> <tr> <th width=60%><font>报警信息</font></th> <th width=10%><font>产品线</font></th> <th width=10%><font>机房</font></th> <th width=20%><font>服务</font></th> </tr> ''' total_message = dict() msg = MIMEMultipart('alternative') msg['Subject'] = "[%s] alarm summary" % time_stamp msg['to'] = ','.join(email) msg['from'] = '*****@*****.**' for message in data: try: status, info, product, idc, service, black = message.split('|') except: continue if black == 'is_black': color = '#ccc' elif black == 'is_not_black': color = '#ffffff' if color not in total_message: total_message[color] = '' body = "<tr bgcolor=%s><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>\n" % \ (color, info, product, idc, service) total_message[color] += body for color in sorted(total_message, reverse=True): header += total_message[color] html_part = MIMEText(header.encode('utf-8'),'html') html_part.set_charset('utf-8') msg.attach(html_part) try: smtp = smtplib.SMTP() smtp.connect("mx.hy01.wandoujia.com",25) smtp.sendmail('*****@*****.**', email, msg.as_string()) except Exception,e: print e
def send_email(fr, to, subject, body): msg = MIMEText(utf8(body)) msg.set_charset('utf8') msg['To'] = utf8(to) msg['From'] = utf8(fr) msg['Subject'] = utf8(subject) global _session if _session is None: _session = _SMTPSession(options.smtp['host'], options.smtp['user'], options.smtp['password'], options.smtp['duration']) _session.send_mail(fr, to, msg.as_string())
def simple_email(to, fr, subj, body): # FIXME: Ugly hack because the templating system has no way to # mark strings as safe, and insists on html-escaping templates for # a text/plain email. body = body.replace('&', '&') def utf8(s): return s.encode('utf8') if isinstance(s, unicode) else s msg = MIMEText(utf8(body)) msg.set_charset('utf8') msg['To'] = utf8(to) msg['From'] = utf8(fr) msg['Subject'] = utf8(subj) send_mail(msg, fr, to)
def send_html_email(self, smtp, send_from, send_pass, send_tos, plain_txt, html_content, title): ''' ''' now = datetime.datetime.now() today = datetime.date.today() msg = MIMEMultipart() body = MIMEMultipart('alternative') msg['Subject'] = Header(title, "utf-8") msg['From'] = send_from text = plain_txt html = """\ <html> <head></head> <body> </body> </html> """ html = html_content try: try: #text = text text = text.decode("GB2312").encode("UTF-8") # except UnicodeDecodeError: print "error:" + text except: print "error:" + text part_text = MIMEText(text, 'plain', 'utf-8') #msg.attach(part_text) body.attach(part_text) except: print 'error text format' print text text = text try: part_html = MIMEText(html, 'html', 'utf-8') part_html.set_charset('utf-8') body.attach(part_html) except: print 'error html format' msg.attach(body) try: smtp_server = smtplib.SMTP() smtp_server.connect(smtp) smtp_server.login(send_from, send_pass) smtp_server.sendmail(send_from, send_tos, msg.as_string()) smtp_server.close() except Exception, e: print "send error:", e
def make_message(short_carrier, subject, body, errors='strict'): cst = { 'D': CHARSET_DOCOMO, 'E': CHARSET_KDDI, 'S': CHARSET_SOFTBANK, 'W': CHARSET_DOCOMO, 'N': CHARSET_DOCOMO, # TODO }[short_carrier] m = MIMEText(body.encode(cst.output_codec, errors), 'plain', cst.output_codec) m.set_charset(cst) m['Subject'] = Header(subject, cst) return m
def make_message(short_carrier, subject, body, errors='strict'): cst = { 'D' : CHARSET_DOCOMO, 'E' : CHARSET_KDDI, 'S' : CHARSET_SOFTBANK, 'W' : CHARSET_DOCOMO, 'N' : CHARSET_DOCOMO, # TODO }[short_carrier] m = MIMEText(body.encode(cst.output_codec, errors), 'plain', cst.output_codec) m.set_charset(cst) m['Subject'] = Header(subject, cst) return m
def send(self, subject, message, receiver): purl = getToolByName(self.context, 'portal_url') mailfrom = purl.getPortalObject().email_from_address mailfrom_name = purl.getPortalObject().email_from_name if mailfrom_name: mailfrom = u"%s <%s>" % (safe_unicode(mailfrom_name), mailfrom) mailhost = getToolByName(self.context, 'MailHost') message = MIMEText(message, _subtype='plain') message.set_charset('utf-8') message['Subject'] = Header(subject, 'utf-8') message['From_'] = Header(mailfrom, 'utf-8') message['From'] = Header(mailfrom, 'utf-8') message['To'] = Header(receiver, 'utf-8') message.add_header('Date', formatdate(localtime=True)) mailhost.send(messageText=message, mto=receiver)
def send_mail(sender, recipients, subject, template, params, cc=None, cc_admin=False, context=None, admin_alternative_email=None): if 'NO_MAIL' in os.environ: return if not cc: cc = [] footer_text = pkg_resources.resource_string( 'pcp.contenttypes.templates', 'footer.txt') params['footer'] = unicode(footer_text, 'utf-8') formatter = Formatter() email_text = pkg_resources.resource_string( 'pcp.contenttypes.templates', template) try: email_text = unicode(email_text, 'utf-8') except UnicodeError: email_text = unicode(email_text, 'iso-8859-15') email_text = formatter.format(email_text, **params) msg = MIMEText(email_text.encode('utf-8'), _charset='utf8') msg.set_charset('utf-8') recipients = [r for r in recipients if r] msg['To'] = ','.join(recipients) if sender: msg['From'] = sender else: portal = plone.api.portal.get() msg['From'] = formataddr( (portal.email_from_name, portal.email_from_address)) if cc_admin: if admin_alternative_email: cc.append(admin_alternative_email) else: cc.append(portal.email_from_address) if cc: msg['CC'] = ','.join(cc) msg['Subject'] = subject if context: PersistentLoggerAdapter(context).log( u'Mail "{}" to {} + {}, Subject: "{}" sent'.format(subject, recipients, cc, subject)) mh = plone.api.portal.get_tool('MailHost') mh.send(msg.as_string(), immediate=True)
def send_html_email(self, smtp, send_from, send_pass, send_tos, plain_txt, html_content, title ): ''' ''' now = datetime.datetime.now() today = datetime.date.today() msg = MIMEMultipart() body = MIMEMultipart('alternative') msg['Subject'] = Header(title, "utf-8") msg['From'] = send_from text = plain_txt html = """\ <html> <head></head> <body> </body> </html> """ html = html_content try: try: #text = text text = text.decode("GB2312").encode("UTF-8")# except UnicodeDecodeError: print "error:" + text except: print "error:" + text part_text = MIMEText(text, 'plain', 'utf-8') #msg.attach(part_text) body.attach(part_text) except: print 'error text format' print text text = text try: part_html = MIMEText(html, 'html', 'utf-8') part_html.set_charset('utf-8') body.attach(part_html) except: print 'error html format' msg.attach(body) try: smtp_server = smtplib.SMTP() smtp_server.connect(smtp) smtp_server.login(send_from, send_pass) smtp_server.sendmail(send_from, send_tos, msg.as_string()) smtp_server.close() except Exception, e: print "send error:", e
def send_email(fr, to, subject, body): msg = MIMEText(utf8(body)) msg.set_charset('utf8') msg['To'] = utf8(to) msg['From'] = utf8(fr) msg['Subject'] = utf8(subject) global _session if _session is None: _session = _SMTPSession(options.smtp['host'], options.smtp['user'], options.smtp['password'], options.smtp['duration'], options.smtp['tls']) _session.send_mail(fr, to, msg.as_string())
def send_digest(json_file, from_addr, username, password, to_addr): server = smtplib.SMTP(host='smtp.gmail.com', port=587) server.ehlo() server.starttls() server.login(username, password) # with open(json_file) as data_file: # journal_article = json.load(data_file) # print (json.dumps(journal_article)) f = codecs.open(json_file, "r", "utf-8") msg = MIMEText(f.read().rstrip("\n"), 'html', 'utf-8') msg['From'] = from_addr msg['To'] = to_addr msg['Subject'] = "New digest" msg.set_charset('utf-8') server.sendmail(from_addr, to_addr, msg.as_string()) server.quit()
def to_MIMEText(self): def utf8(s, reject_newlines=True): if reject_newlines and '\n' in s: raise HeaderParseError( 'header value contains unexpected newline: {!r}'.format(s)) return s.encode('utf8') if isinstance(s, unicode) else s fr = '"%s" <%s>' % ( self.from_name().replace('"', ''), self.fr_addr.replace('>', ''), ) # Addresses that start with a dash could confuse poorly-written # software's argument parsers, and thus are disallowed by default in # Postfix: http://www.postfix.org/postconf.5.html#allow_min_user if not fr.startswith('-') and not self.to_addr.startswith('-'): if self.html_body: msg = MIMEMultipart("alternative") if self.body: part1 = MIMEText(utf8(self.body, reject_newlines=False), 'plain') part1.set_charset('utf8') msg.attach(part1) part2 = MIMEText(utf8(self.html_body, reject_newlines=False), 'html') part2.set_charset('utf8') msg.attach(part2) else: msg = MIMEText(utf8(self.body, reject_newlines=False), 'plain') msg.set_charset('utf8') msg['To'] = utf8(self.to_addr) msg['From'] = utf8(fr) msg['Subject'] = utf8(self.subject) timestamp = time.mktime(self.date.timetuple()) msg['Date'] = utf8(email.utils.formatdate(timestamp)) if self.user: msg['X-Reddit-username'] = utf8(self.user.name) msg['X-Reddit-ID'] = self.msg_hash if self.reply_to: msg['Reply-To'] = utf8(self.reply_to) if self.list_unsubscribe_header: msg.add_header('List-Unsubscribe', self.list_unsubscribe_header) return msg return None
def advancedSendMail( send_from, send_to, subject, text, html, cc_to = [], files = [], server = "192.168.42.13" ): assert type( send_to ) == list assert type( files ) == list if not text and not html: raise "No content to send!" elif text and not html : msg = MIMEText( text, "plain" ) elif not text and html: msg = MIMEText( html, "html", "utf-8" ) else: msg = MIMEMultipart( "alternative" ) msg.attach( MIMEText( text, "plain" ) ) msg.attach( MIMEText( html, "html" ) ) msg.set_charset( "utf-8" ) if len( files ) > 0 : tmpmsg = msg msg = MIMEMultipart() msg.attach( tmpmsg ) msg['From'] = send_from msg['To'] = COMMASPACE.join( send_to ) if cc_to: assert type( cc_to ) == list msg['cc'] = COMMASPACE.join( cc_to ) send_to.extend( cc_to ) msg['Date'] = formatdate( localtime = True ) msg['Subject'] = subject for f in files: part = MIMEBase( 'application', "octet-stream" ) if isinstance( f, basestring ): part.set_payload( open( f, "rb" ).read() ) Encoders.encode_base64( part ) part.add_header( 'Content-Disposition', 'attachment; filename="%s"' % Header( os.path.basename( f ), 'utf-8' ) ) elif hasattr( f, "file_path" ) and hasattr( f, "file_name" ): part.set_payload( open( f.file_path, "rb" ).read() ) Encoders.encode_base64( part ) part.add_header( 'Content-Disposition', 'attachment; filename="%s"' % Header( f.file_name, 'utf-8' ) ) msg.attach( part ) smtp = smtplib.SMTP( server ) smtp.sendmail( send_from, send_to, msg.as_string() ) smtp.close()
def to_MIMEText(self): def utf8(s): return s.encode('utf8') if isinstance(s, unicode) else s fr = '"%s" <%s>' % (self.from_name(), self.fr_addr) if not fr.startswith('-') and not self.to_addr.startswith('-'): # security msg = MIMEText(utf8(self.body)) msg.set_charset('utf8') msg['To'] = utf8(self.to_addr) msg['From'] = utf8(fr) msg['Subject'] = utf8(self.subject) if self.user: msg['X-Reddit-username'] = utf8(self.user.name) msg['X-Reddit-ID'] = self.msg_hash if self.reply_to: msg['Reply-To'] = utf8(self.reply_to) return msg return None
def mejl(self, tabelka, ustawieniaMejla): od, do, smtp = tuple( [ustawieniaMejla[x] for x in ["od", "do", "smtp"]]) tekst = u"<h2>Wyniki</h2><ul>" poprzedniDzien = "" for wiersz in tabelka: if wiersz[0] != poprzedniDzien: tekst = tekst + "</ul><h4>%s</h4><ul>" % wiersz[0].strftime( "%A, %Y-%m-%d") reprezentacja = self.pozbadzSiePolskichLiter( "%s" % (", ".join(wiersz[1:]))) style = "" if not self.sprawdzCzyJuzSpotkalismy("%s" % wiersz[0] + reprezentacja): style = " style='color: green'" tekst = tekst + "<li%s>%s</li>" % (style, reprezentacja) poprzedniDzien = wiersz[0] tekst = tekst + "</ul><br/><br/>" tekst = tekst + ("<br/>\r-- " + "<br/>\r %s") % datetime.datetime.now().__str__() temat = "[%s] %s" % (self.naglowekWMejlu, datetime.datetime.now()) charset = Charset('utf-8') tresc = MIMEText(tekst.encode('utf-8'), 'html') tresc.set_charset(charset) tresc['From'] = od tresc['To'] = ", ".join(do) tresc['Subject'] = temat if ustawieniaMejla.get('smtp_tls'): smtp_pass = hasla.haslo(smtp, od, ustawieniaMejla.get('smtp_password')) serwer = smtplib.SMTP(smtp, 587) serwer.starttls() serwer.login(od, smtp_pass) else: serwer = smtplib.SMTP(smtp) serwer.sendmail(od, do, tresc.as_string()) serwer.quit()
def send_mail(self, **config): # config['mail_to'] # config['mail_cc'] None # config['mail_bcc'] None # config['subject'] # config['msg'] # config['coding'] utf-8 # config['server'] mail.pptv.com # config['port'] 587 config.setdefault('mail_cc', None) config.setdefault('mail_bcc', None) config.setdefault('coding', 'utf-8') config.setdefault('server', 'smtp.vipshop.com') config.setdefault('port', 25) import smtplib from email.MIMEText import MIMEText msg = MIMEText(config['msg'], 'html', _charset=config['coding']) msg.set_charset(config['coding']) msg['From'] = self.mail_from msg['Subject'] = config['subject'] if isinstance(config['mail_to'], list): msg['To'] = ','.join(config['mail_to']) else: msg['To'] = config['mail_to'] if isinstance(config['mail_cc'], list): msg['Cc'] = ','.join(config['mail_cc']) else: msg['Cc'] = config['mail_cc'] if isinstance(config['mail_bcc'], list): msg['Bcc'] = ','.join(config['mail_bcc']) else: msg['Bcc'] = config['mail_bcc'] server = smtplib.SMTP() server.connect(config['server'], config['port']) server.login(self.user, self.passwd) server.sendmail(self.mail_from, config['mail_to'], msg.as_string()) server.quit()
def _do_send(self, transport, event, format, recipients, formatter, pubkey_ids=[]): output = formatter.format(transport, event.realm, format, event) # DEVEL: force message body plaintext style for crypto operations if self.crypto != '' and pubkey_ids != []: if self.crypto == 'sign': output = self.enigma.sign(output, self.private_key) elif self.crypto == 'encrypt': output = self.enigma.encrypt(output, pubkey_ids) elif self.crypto == 'sign,encrypt': output = self.enigma.sign_encrypt(output, pubkey_ids, self.private_key) self.log.debug(output) self.log.debug(_("EmailDistributor crypto operaton successful.")) alternate_output = None else: alternate_style = formatter.alternative_style_for( transport, event.realm, format) if alternate_style: alternate_output = formatter.format(transport, event.realm, alternate_style, event) else: alternate_output = None # sanity check if not self._charset.body_encoding: try: dummy = output.encode('ascii') except UnicodeDecodeError: raise TracError(_("Ticket contains non-ASCII chars. " \ "Please change encoding setting")) rootMessage = MIMEMultipart("related") headers = dict() if self.set_message_id: # A different, predictable, but still sufficiently unique # message ID will be generated as replacement in # announcer.email_decorators.generic.ThreadingEmailDecorator # for email threads to work. headers['Message-ID'] = self._message_id(event.realm) headers['Date'] = formatdate() from_header = formataddr((self.from_name or self.env.project_name, self.email_from)) headers['From'] = from_header headers['To'] = '"%s"' % (self.to) if self.use_public_cc: headers['Cc'] = ', '.join([x[2] for x in recipients if x]) headers['Reply-To'] = self.replyto for k, v in headers.iteritems(): set_header(rootMessage, k, v) rootMessage.preamble = 'This is a multi-part message in MIME format.' if alternate_output: parentMessage = MIMEMultipart('alternative') rootMessage.attach(parentMessage) alt_msg_format = 'html' in alternate_style and 'html' or 'plain' msgText = MIMEText(alternate_output, alt_msg_format) parentMessage.attach(msgText) else: parentMessage = rootMessage msg_format = 'html' in format and 'html' or 'plain' msgText = MIMEText(output, msg_format) del msgText['Content-Transfer-Encoding'] msgText.set_charset(self._charset) parentMessage.attach(msgText) decorators = self._get_decorators() if len(decorators) > 0: decorator = decorators.pop() decorator.decorate_message(event, rootMessage, decorators) recip_adds = [x[2] for x in recipients if x] # Append any to, cc or bccs added to the recipient list for field in ('To', 'Cc', 'Bcc'): if rootMessage[field] and \ len(str(rootMessage[field]).split(',')) > 0: for addy in str(rootMessage[field]).split(','): self._add_recipient(recip_adds, addy) # replace with localized bcc hint if headers['To'] == 'undisclosed-recipients: ;': set_header(rootMessage, 'To', _('undisclosed-recipients: ;')) self.log.debug("Content of recip_adds: %s" % (recip_adds)) package = (from_header, recip_adds, rootMessage.as_string()) start = time.time() if self.use_threaded_delivery: self.get_delivery_queue().put(package) else: self.send(*package) stop = time.time() self.log.debug("EmailDistributor took %s seconds to send."\ %(round(stop-start,2)))
def send_message(self, issueid, msgid, note, sendto, from_address=None, bcc_sendto=[], crypt=False): '''Actually send the nominated message from this issue to the sendto recipients, with the note appended. ''' users = self.db.user messages = self.db.msg files = self.db.file if msgid is None: inreplyto = None messageid = None else: inreplyto = messages.get(msgid, 'inreplyto') messageid = messages.get(msgid, 'messageid') # make up a messageid if there isn't one (web edit) if not messageid: # this is an old message that didn't get a messageid, so # create one messageid = "<%s.%s.%s%s@%s>" % (time.time(), random.random(), self.classname, issueid, self.db.config.MAIL_DOMAIN) if msgid is not None: messages.set(msgid, messageid=messageid) # compose title cn = self.classname title = self.get(issueid, 'title') or '%s message copy' % cn # figure author information if msgid: authid = messages.get(msgid, 'author') else: authid = self.db.getuid() authname = users.get(authid, 'realname') if not authname: authname = users.get(authid, 'username', '') authaddr = users.get(authid, 'address', '') if authaddr and self.db.config.MAIL_ADD_AUTHOREMAIL: authaddr = " <%s>" % formataddr(('', authaddr)) elif authaddr: authaddr = "" # make the message body m = [''] # put in roundup's signature if self.db.config.EMAIL_SIGNATURE_POSITION == 'top': m.append(self.email_signature(issueid, msgid)) # add author information if authid and self.db.config.MAIL_ADD_AUTHORINFO: if msgid and len(self.get(issueid, 'messages')) == 1: m.append( _("New submission from %(authname)s%(authaddr)s:") % locals()) elif msgid: m.append( _("%(authname)s%(authaddr)s added the comment:") % locals()) else: m.append(_("Change by %(authname)s%(authaddr)s:") % locals()) m.append('') # add the content if msgid is not None: m.append(messages.get(msgid, 'content', '')) # get the files for this message message_files = [] if msgid: for fileid in messages.get(msgid, 'files'): # check the attachment size filesize = self.db.filesize('file', fileid, None) if filesize <= self.db.config.NOSY_MAX_ATTACHMENT_SIZE: message_files.append(fileid) else: base = self.db.config.TRACKER_WEB link = "".join((base, files.classname, fileid)) filename = files.get(fileid, 'name') m.append( _("File '%(filename)s' not attached - " "you can download it from %(link)s.") % locals()) # add the change note if note: m.append(note) # put in roundup's signature if self.db.config.EMAIL_SIGNATURE_POSITION == 'bottom': m.append(self.email_signature(issueid, msgid)) # figure the encoding charset = getattr(self.db.config, 'EMAIL_CHARSET', 'utf-8') # construct the content and convert to unicode object body = unicode('\n'.join(m), 'utf-8').encode(charset) # make sure the To line is always the same (for testing mostly) sendto.sort() # make sure we have a from address if from_address is None: from_address = self.db.config.TRACKER_EMAIL # additional bit for after the From: "name" from_tag = getattr(self.db.config, 'EMAIL_FROM_TAG', '') if from_tag: from_tag = ' ' + from_tag subject = '[%s%s] %s' % (cn, issueid, title) author = (authname + from_tag, from_address) # send an individual message per recipient? if self.db.config.NOSY_EMAIL_SENDING != 'single': sendto = [[address] for address in sendto] else: sendto = [sendto] # tracker sender info tracker_name = unicode(self.db.config.TRACKER_NAME, 'utf-8') tracker_name = nice_sender_header(tracker_name, from_address, charset) # now send one or more messages # TODO: I believe we have to create a new message each time as we # can't fiddle the recipients in the message ... worth testing # and/or fixing some day first = True for sendto in sendto: # create the message mailer = Mailer(self.db.config) message = mailer.get_standard_message(multipart=message_files) # set reply-to to the tracker message['Reply-To'] = tracker_name # message ids if messageid: message['Message-Id'] = messageid if inreplyto: message['In-Reply-To'] = inreplyto # Generate a header for each link or multilink to # a class that has a name attribute for propname, prop in self.getprops().items(): if not isinstance(prop, (hyperdb.Link, hyperdb.Multilink)): continue cl = self.db.getclass(prop.classname) if not 'name' in cl.getprops(): continue if isinstance(prop, hyperdb.Link): value = self.get(issueid, propname) if value is None: continue values = [value] else: values = self.get(issueid, propname) if not values: continue values = [cl.get(v, 'name') for v in values] values = ', '.join(values) header = "X-Roundup-%s-%s" % (self.classname, propname) try: message[header] = values.encode('ascii') except UnicodeError: message[header] = Header(values, charset) if not inreplyto: # Default the reply to the first message msgs = self.get(issueid, 'messages') # Assume messages are sorted by increasing message number here # If the issue is just being created, and the submitter didn't # provide a message, then msgs will be empty. if msgs and msgs[0] != msgid: inreplyto = messages.get(msgs[0], 'messageid') if inreplyto: message['In-Reply-To'] = inreplyto # attach files if message_files: # first up the text as a part part = MIMEText(body) part.set_charset(charset) encode_quopri(part) message.attach(part) for fileid in message_files: name = files.get(fileid, 'name') mime_type = files.get(fileid, 'type') content = files.get(fileid, 'content') if mime_type == 'text/plain': try: content.decode('ascii') except UnicodeError: # the content cannot be 7bit-encoded. # use quoted printable # XXX stuffed if we know the charset though :( part = MIMEText(content) encode_quopri(part) else: part = MIMEText(content) part['Content-Transfer-Encoding'] = '7bit' elif mime_type == 'message/rfc822': main, sub = mime_type.split('/') p = FeedParser() p.feed(content) part = MIMEBase(main, sub) part.set_payload([p.close()]) else: # some other type, so encode it if not mime_type: # this should have been done when the file was saved mime_type = mimetypes.guess_type(name)[0] if mime_type is None: mime_type = 'application/octet-stream' main, sub = mime_type.split('/') part = MIMEBase(main, sub) part.set_payload(content) Encoders.encode_base64(part) cd = 'Content-Disposition' part[cd] = 'attachment;\n filename="%s"' % name message.attach(part) else: message.set_payload(body) encode_quopri(message) if crypt: send_msg = self.encrypt_to(message, sendto) else: send_msg = message mailer.set_message_attributes(send_msg, sendto, subject, author) if crypt: send_msg['Message-Id'] = message['Message-Id'] send_msg['Reply-To'] = message['Reply-To'] if message.get('In-Reply-To'): send_msg['In-Reply-To'] = message['In-Reply-To'] mailer.smtp_send(sendto, send_msg.as_string()) if first: if crypt: # send individual bcc mails, otherwise receivers can # deduce bcc recipients from keys in message for bcc in bcc_sendto: send_msg = self.encrypt_to(message, [bcc]) send_msg['Message-Id'] = message['Message-Id'] send_msg['Reply-To'] = message['Reply-To'] if message.get('In-Reply-To'): send_msg['In-Reply-To'] = message['In-Reply-To'] mailer.smtp_send([bcc], send_msg.as_string()) elif bcc_sendto: mailer.smtp_send(bcc_sendto, send_msg.as_string()) first = False
fichierHTML = open(raw_input("-> Chemin de la page HTML : "), "r").read() with open('liste_clients.txt') as clients: for email in clients: # FORMATTAGE DU MAIL mail = MIMEMultipart() mail.set_charset("utf-8") mail['From'] = infos[1] mail['Subject'] = infos[2] mail['To'] = email mail['Content-Type'] = "text/html; charset=utf-8" emailtext = MIMEText(fichierHTML, 'html') emailtext.set_charset('utf-8') mail.attach(emailtext) # CONFIGURATION DU SMTP serv = smtplib.SMTP(infos[0]) print "Configuration du serveur smtp : OK!" # ENVOI DU MAIL ANONYME serv.sendmail(infos[1], email, mail.as_string()) print "Le message est envoyé a " + email serv.quit() ################################## ## SCRIPT REALISE PAR FRAX2602 ##
def send(self, torcpts, ccrcpts, mime_headers={}): """ this method is based NotifyEmail in trac/notification.py As the default trac NotifyEmail class assumes alot, and will overwrite headers we do not call our ancestor class method here, but send the mail direct """ from email.MIMEText import MIMEText from email.Utils import formatdate stream = self.template.generate(**self.data) body = stream.render('text') projname = self.config.get('project', 'name') headers = {} headers['X-Mailer'] = 'Trac %s, by Edgewall Software' % __version__ headers['X-Trac-Version'] = __version__ headers['X-Trac-Project'] = projname headers['X-URL'] = self.env.project_url headers['Precedence'] = 'bulk' headers['Auto-Submitted'] = 'auto-generated' headers['Subject'] = self.subject headers['From'] = (self.from_name or projname, self.from_email) headers['Reply-To'] = self.reply_to_email # add Message-ID and In-Reply-To for threaded mail clients if self.action == 'post_created': headers['Message-ID'] = self.get_message_id(projname, self.blog.name) else: headers['Message-ID'] = self.get_message_id(projname, self.blog.name, self.time) headers['In-Reply-To'] = headers['References'] = self.get_message_id(projname, self.blog.name) def build_addresses(rcpts): """Format and remove invalid addresses""" return filter(lambda x: x, [self.get_smtp_address(addr) for addr in rcpts]) def remove_dup(rcpts, all): """Remove duplicates""" tmp = [] for rcpt in rcpts: if not rcpt in all: tmp.append(rcpt) all.append(rcpt) return (tmp, all) toaddrs = build_addresses(torcpts) ccaddrs = build_addresses(ccrcpts) accparam = self.config.getlist('fullblog-notification', 'smtp_always_cc') accaddrs = accparam and build_addresses(accparam) or [] recipients = [] (toaddrs, recipients) = remove_dup(toaddrs, recipients) (ccaddrs, recipients) = remove_dup(ccaddrs, recipients) (accaddrs, recipients) = remove_dup(accaddrs, recipients) # if there is not valid recipient, leave immediately if len(recipients) < 1: self.env.log.info('no recipient for a fullblog notification') return cc = accaddrs + ccaddrs if cc: headers['Cc'] = ', '.join(cc) if toaddrs: headers['To'] = ', '.join(toaddrs) headers['Date'] = formatdate() # sanity check if not self._charset.body_encoding: try: dummy = body.encode('ascii') except UnicodeDecodeError: raise TracError(_("Blog post contains non-Ascii chars. " \ "Please change encoding setting")) msg = MIMEText(body, 'plain') # Message class computes the wrong type from MIMEText constructor, # which does not take a Charset object as initializer. Reset the # encoding type to force a new, valid evaluation del msg['Content-Transfer-Encoding'] msg.set_charset(self._charset) self.add_headers(msg, headers); self.add_headers(msg, mime_headers); self.env.log.info("Sending SMTP notification to %s:%d to %s" % (self.smtp_server, self.smtp_port, recipients)) msgtext = msg.as_string() # Ensure the message complies with RFC2822: use CRLF line endings recrlf = re.compile("\r?\n") msgtext = CRLF.join(recrlf.split(msgtext)) try: self.server.sendmail(msg['From'], recipients, msgtext) except Exception, err: self.env.log.debug('Notification could not be sent: %r', err)
def send(self, torcpts, ccrcpts, mime_headers={}): from email.MIMEText import MIMEText from email.Utils import formatdate, formataddr body = self.hdf.render(self.template_name) projname = self.config.get('project', 'name') public_cc = self.config.getbool('notification', 'use_public_cc') headers = {} headers['X-Mailer'] = 'Trac %s, by Edgewall Software' % __version__ headers['X-Trac-Version'] = __version__ headers['X-Trac-Project'] = projname headers['X-URL'] = self.config.get('project', 'url') headers['Subject'] = self.subject headers['From'] = (projname, self.from_email) headers['Sender'] = self.from_email headers['Reply-To'] = self.replyto_email def build_addresses(rcpts): """Format and remove invalid addresses""" return filter(lambda x: x, \ [self.get_smtp_address(addr) for addr in rcpts]) def remove_dup(rcpts, all): """Remove duplicates""" tmp = [] for rcpt in rcpts: if not rcpt in all: tmp.append(rcpt) all.append(rcpt) return (tmp, all) toaddrs = build_addresses(torcpts) ccaddrs = build_addresses(ccrcpts) accparam = self.config.get('notification', 'smtp_always_cc') accaddrs = accparam and \ build_addresses(accparam.replace(',', ' ').split()) or [] bccparam = self.config.get('notification', 'smtp_always_bcc') bccaddrs = bccparam and \ build_addresses(bccparam.replace(',', ' ').split()) or [] recipients = [] (toaddrs, recipients) = remove_dup(toaddrs, recipients) (ccaddrs, recipients) = remove_dup(ccaddrs, recipients) (accaddrs, recipients) = remove_dup(accaddrs, recipients) (bccaddrs, recipients) = remove_dup(bccaddrs, recipients) # if there is not valid recipient, leave immediately if len(recipients) < 1: self.env.log.info('no recipient for a ticket notification') return pcc = accaddrs if public_cc: pcc += ccaddrs if toaddrs: headers['To'] = ', '.join(toaddrs) if pcc: headers['Cc'] = ', '.join(pcc) headers['Date'] = formatdate() # sanity check if not self._charset.body_encoding: try: dummy = body.encode('ascii') except UnicodeDecodeError: raise TracError, "Ticket contains non-Ascii chars. " \ "Please change encoding setting" msg = MIMEText(body, 'plain') # Message class computes the wrong type from MIMEText constructor, # which does not take a Charset object as initializer. Reset the # encoding type to force a new, valid evaluation del msg['Content-Transfer-Encoding'] msg.set_charset(self._charset) self.add_headers(msg, headers); self.add_headers(msg, mime_headers); self.env.log.debug("Sending SMTP notification to %s on port %d to %s" % (self.smtp_server, self.smtp_port, recipients)) msgtext = msg.as_string() # Ensure the message complies with RFC2822: use CRLF line endings recrlf = re.compile("\r?\n") msgtext = "\r\n".join(recrlf.split(msgtext)) self.server.sendmail(msg['From'], recipients, msgtext)
def send(self, torcpts, ccrcpts, mime_headers={}): from email.MIMEText import MIMEText from email.Utils import formatdate stream = self.template.generate(**self.data) # don't translate the e-mail stream t = deactivate() try: body = stream.render('text', encoding='utf-8') finally: reactivate(t) public_cc = self.config.getbool('notification', 'use_public_cc') headers = { 'X-Mailer': 'Trac %s, by Edgewall Software' % __version__, 'X-Trac-Version': __version__, 'X-Trac-Project': self.env.project_name, 'X-URL': self.env.project_url, 'Precedence': 'bulk', 'Auto-Submitted': 'auto-generated', 'Subject': self.subject, 'From': (self.from_name, self.from_email) if self.from_name else self.from_email, 'Reply-To': self.replyto_email } def build_addresses(rcpts): """Format and remove invalid addresses""" return filter(lambda x: x, [self.get_smtp_address(addr) for addr in rcpts]) def remove_dup(rcpts, all): """Remove duplicates""" tmp = [] for rcpt in rcpts: if not rcpt in all: tmp.append(rcpt) all.append(rcpt) return tmp, all notify_sys = NotificationSystem(self.env) toaddrs = build_addresses(torcpts) ccaddrs = build_addresses(ccrcpts) accaddrs = notify_sys.smtp_always_cc_list bccaddrs = notify_sys.smtp_always_bcc_list recipients = [] toaddrs, recipients = remove_dup(toaddrs, recipients) ccaddrs, recipients = remove_dup(ccaddrs, recipients) accaddrs, recipients = remove_dup(accaddrs, recipients) bccaddrs, recipients = remove_dup(bccaddrs, recipients) # if there is not valid recipient, leave immediately if len(recipients) < 1: self.env.log.info("no recipient for a ticket notification") return pcc = accaddrs if public_cc: pcc += ccaddrs if toaddrs: headers['To'] = ', '.join(toaddrs) if pcc: headers['Cc'] = ', '.join(pcc) headers['Date'] = formatdate() msg = MIMEText(body, 'plain') # Message class computes the wrong type from MIMEText constructor, # which does not take a Charset object as initializer. Reset the # encoding type to force a new, valid evaluation del msg['Content-Transfer-Encoding'] msg.set_charset(self._charset) self.add_headers(msg, headers) self.add_headers(msg, mime_headers) NotificationSystem(self.env).send_email(self.from_email, recipients, msg.as_string())