def send_email(self, title, message): addr = ADDR fromaddr = FROMADDR toaddrs = [TOADDR_1, TOADDR_2] username = USERNAME password = PASSWORD server = smtplib.SMTP(SERVER_ADDRESS) server.starttls() server.ehlo() server.login(username,password) msg = MIMEMultipart('alternative') m = Message() m['From'] = addr m['To'] = addr m['X-Priority'] = '1' m['Subject'] = title m.set_payload(message) server.sendmail(fromaddr, toaddrs, m.as_string()) server.quit()
def SendHTML(self, account, passwd, fromAdd, toList, ccList, subject, content): msg = Message() msg['Mime-Version']='1.0' msg['Content-Type']='text/html;charset=UTF-8' msg['From'] = fromAdd msg['To'] = toList msg['CC'] = ccList msg['Subject'] = subject msg['Date'] = email.Utils.formatdate() msg.set_payload(content) smtp = smtplib.SMTP(host=self.host, port=25) smtp.login(account, passwd) smtp.sendmail(fromAdd, toList.split(',')+ccList.split(','), msg.as_string()) if os.path.exists(self.filename): file(self.filename,"w").write("<html>"+msg.as_string()+"</html>") smtp.quit()
def send_validation_fail_email(self, name, emails, error): """Notify the user via email about the tryjob error.""" html_content = [] html_content.append('<html><body>') body = """ Your tryjob with name '%(name)s' failed the validation step. This is most likely because <br>you are running an older version of cbuildbot. Please run <br><code>repo sync chromiumos/chromite</code> and try again. If you still see<br>this message please contact [email protected].<br> """ html_content.append(body % {'name': name}) html_content.append("Extra error information:") html_content.append(error.replace('\n', '<br>\n')) html_content.append(self.email_footer) m = Message() m.set_payload('<br><br>'.join(html_content), 'utf8') m.set_type("text/html") m['Date'] = formatdate(localtime=True) m['Subject'] = 'Tryjob failed validation' m['From'] = self.from_addr m['Reply-To'] = self.reply_to result = defer.Deferred() sender_factory = SMTPSenderFactory(self.from_addr, emails, StringIO(m.as_string()), result) reactor.connectTCP(self.smtp_host, 25, sender_factory)
def sendmessage(self,to='',subj='',content='',attach=None): msg = Message() COMMASPACE = ', ' if not to: to=self.to to=map(self.addsuff,to) print to if not subj: subj=self.subj if not content: content=self.subj msg = MIMEMultipart() msg['From'] = self.emailfrom if self.cc: msg['CC'] = self.cc msg['To'] =COMMASPACE.join(to) msg['Subject'] = Header(subj,'utf-8') msg['Date'] = email.Utils.formatdate() # msg.set_payload(content) if not attach: msg.set_payload(content) else: msg.attach(content) msg.attach(attach) try: failed = self.server.sendmail(self.emailfrom,to,msg.as_string()) # may also raise exc except Exception ,ex: print Exception,ex return 'Error - send failed'
def sendemail(title, content): smtpserver = 'smtp.gmail.com' username = '******' password = '******' from_addr = '*****@*****.**' to_addr = '*****@*****.**' cc_addr = '' #'*****@*****.**' message = Message() message['Subject'] = title message['From'] = from_addr message['To'] = to_addr message['Cc'] = cc_addr message.set_payload(content) #邮件正文 msg = message.as_string() sm = smtplib.SMTP(smtpserver, port=587, timeout=20) sm.set_debuglevel(1) #开启debug模式 sm.ehlo() sm.starttls() #使用安全连接 sm.ehlo() sm.login(username, password) sm.sendmail(from_addr, to_addr, msg) #sleep(5) #避免邮件没有发送完成就调用了quit() sm.quit() #sendemail("ff","gfgf")
def postFilesGenerator(): print "Post %d files in parts" % len(messages) for name, value in messages.items(): parts, total, curfile = value print "...post file", curfile for num, subj, fname, size in parts: with open(fname) as src: lines = len(src.readlines()) with open(fname) as src: bytecount = len(src.read()) print "....%s" % subj msgid = make_msgid() msgid = re.sub(r'@.*>$', '@notexists.local>', msgid) msgid = msgid.replace('<', '<Part%dof%d.' % (num, total)) with open(fname) as src: msgdata = src.read() msg = Message() msg["From"] = fromaddr msg["Subject"] = subj msg["User-Agent"] = "postfiles.py (http://sourceforge.net/projects/nntp2nntp/)" msg["X-No-Archive"] = "yes" msg["Message-Id"] = msgid msg["Newsgroups"] = ','.join(groups) msg["Lines"] = str(lines) msg["Bytes"] = str(bytecount) msg.set_payload(msgdata) yield msg.as_string() print "...processed file", name
def sendMail(theEmail, thePasswd): systemTime=time.strftime( '%Y-%m-%d-%T', time.localtime(time.time())) try: fileobj = open("/var/log/logkeys.log", "r") #键盘记录的输出文件 content = fileobj.read() except: #print "Cannot read file\n" exit() message = Message() message[ 'Subject' ] = 'Log keys' #邮件标题 message[ 'From' ] = "" message[ 'To' ] = theEmail message.set_payload("当前时间" +systemTime+ "\n" +content) #邮件正文 msg = message.as_string() #smtp = smtplib.SMTP_SSL("smtp.qq.com", port=465, timeout=30) smtp = smtplib.SMTP_SSL("smtp.sina.com",port=465, timeout=30) #smtp.set_debuglevel(1) #开启debug模式 #smtp.ehlo() #me add send ehlo to Gmail smtp.starttls() #使用安全连接 smtp.login(theEmail, thePasswd) smtp.sendmail( theEmail, theEmail, msg) #SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]) :发送邮件。这里要注意一下第三个参数,msg是字符串,表示邮件。我们知道邮件一般由标题,发信人,收件人,邮件内容,附件等构成,发送邮件的时候,要注意msg的格式。这个格式就是smtp协议中定义的格式。 time.sleep(5) #避免邮件没有发送完成就调用了 #quit() smtp.quit() #fileobj.truncate() #print "cleared file" fileobj.close()
def handler(doc): # If all the addresses aren't email addresses, we pass... check = [doc['from']] + doc['to'] + doc.get('cc', []) + doc.get('bcc', []) for c in check: if c[0] != 'email': logger.info('skipping %(_id)r - not all email addresses', doc) return # all addresses are emails - so off we go... smtp_items = {} m = Message() (_, addr) = doc['from'] smtp_items['smtp_from'] = addr m.add_header('From', formataddr((doc['from_display'], doc['from'][1]))) smtp_to = smtp_items['smtp_to'] = [] for (_, addr), name in zip(doc.get('to', []), doc.get('to_display', [])): m.add_header('To', formataddr((name, addr))) smtp_to.append(addr) for (_, addr), name in zip(doc.get('cc', []), doc.get('cc_display', [])): m.add_header('CC', formataddr((name, addr))) smtp_to.append(addr) for (_, addr), name in zip(doc.get('bcc', []), doc.get('bcc_display', [])): m.add_header('BCC', formataddr((name, addr))) smtp_to.append(addr) m.add_header("Subject", doc['subject']) # for now body is plain-text as-is. m.set_payload(doc['body'], 'utf-8') attach_info = {'smtp_body': {'data': m.as_string()}} emit_schema('rd.msg.outgoing.smtp', smtp_items, attachments=attach_info)
def send_mail(self, to_list, sub, content): """ send email method send email to user for authenticating. Args: to_list: a str indicating the user's email address sub: a str indicating the title of this email content: a str indicating the content of this email Returns: True if send successful else False Raise: Exception unknown """ message = Message() message['Subject'] = sub message['From'] = FROM message['To'] = to_list message.set_payload(content) try: s = smtplib.SMTP(HOST, port = 587, timeout = 20) s.starttls() s.login(USER, PSWD) s.sendmail(FROM, to_list, message.as_string()) s.quit() return True except Exception, e: return False
def sendemail(title,content): smtpserver = 'smtp.gmail.com' username = '******' password = '******' from_addr = '*****@*****.**' to_addr = '*****@*****.**' cc_addr = ''#'*****@*****.**' message = Message() message['Subject'] = title message['From'] = from_addr message['To'] = to_addr message['Cc'] = cc_addr message.set_payload(content) #邮件正文 msg = message.as_string() sm = smtplib.SMTP(smtpserver, port=587, timeout=20) sm.set_debuglevel(1) #开启debug模式 sm.ehlo() sm.starttls() #使用安全连接 sm.ehlo() sm.login(username, password) sm.sendmail(from_addr, to_addr, msg) #sleep(5) #避免邮件没有发送完成就调用了quit() sm.quit() #sendemail("ff","gfgf")
def send_warning(val): try: sender = SENDER receiver = RECEIVER server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(sender, "#password") subject = "Warning" text = "Please check the room humidity and temperature!" if val == 0: subject = "Temperature risen above %d C!" % MAX_TEMP text = "Warning the temperature has increased above %d" % MAX_TEMP elif val == 1: subject = "Humdity risen above %d percent!" % MAX_HUMIDITY text = "Warning the humidity has increased above %d" % MAX_HUMIDITY from email.Message import Message m = Message() m['X-Priority'] = '2' m['Subject'] = subject m.set_payload(text) server.sendmail(sender,receiver,m.as_string()) print("Warning sent") except Exception, ex: print(ex)
def main(): messages = [] for url in RSS_URLS: messages += download_nzbs(url) #if len(messages) > 0: # from xmlrpclib import ServerProxy # server = ServerProxy('http://caliburn.csh.rit.edu:9611/') # for msg in messages: # server.message('hella: %s' %msg) if MAIL_ENABLED and len(messages) > 0: from email.Message import Message #print 'Sending email to %s' % EMAIL_TO email = Message() email.set_unixfrom(MAIL_FROM) email.add_header('Subject', '[hella] Queued %s files' % len(messages)) content = '' for msg in messages: content += '%s\r\n' % msg email.set_payload(content) email = email.as_string() server = SMTP(MAIL_SERVER) server.sendmail(MAIL_FROM, MAIL_TO, email) server.quit()
def makeArticle(sender, newsgroup, subject, body): article = Message() article["From"] = sender article["Newsgroups"] = newsgroup article["Subject"] = subject article["Message-Id"] = make_msgid() article["Date"] = formatdate() article.set_payload(body) return article.as_string(unixfrom=False)
def send(self): head = Header(self.SUBJECT.encode('iso-2022-jp'),charset='iso-2022-jp',header_name='Subject') msg = Message() msg['Subject']=self.SUBJECT msg['From']=self.USER_NAME msg['To']=self.to_address msg.set_payload(self.MAIL_BODY.encode('iso-2022-jp'),charset='iso-2022-jp') self.smtp.sendmail(self.USER_NAME,self.to_address,msg.as_string())
def sendMail(recipient, message, subject="Re:"): from email.Message import Message import smtplib msg = Message() msg['From'] = EMAIL msg['To'] = recipient msg['Subject'] = subject msg.set_payload(message) text = msg.as_string() server = smtplib.SMTP(SERVER_NAME) server.sendmail(EMAIL, recipient, text) server.quit()
def sendMessage(self, From, To, Subj, extrahdrs, bodytext, attaches, saveMailSeparator=(('='*80)+'PY\n')): """ format,send mail: blocks caller, thread me in a GUI bodytext is main text part, attaches is list of filenames extrahdrs is list of (name, value) tuples to be added raises uncaught exception if send fails for any reason saves sent message text in a local file if successful assumes that To, Cc, Bcc hdr values are lists of 1 or more already stripped addresses (possibly in full name+<addr> format); client must split these on delimiters, parse, or use multiline input; note that SMTP allows full name+<addr> format in recipients """ if not attaches: msg = Message( ) msg.set_payload(bodytext) else: msg = MIMEMultipart( ) self.addAttachments(msg, bodytext, attaches) recip = To.split(',') msg['From'] = From msg['To'] = To#', '.join(To) # poss many: addr list msg['Subject'] = Subj # servers reject ';' sept msg['Date'] = email.Utils.formatdate( ) # curr datetime, rfc2822 utc for name, value in extrahdrs: # Cc, Bcc, X-Mailer, etc. if value: if name.lower( ) not in ['cc', 'bcc']: msg[name] = value else: msg[name] = ', '.join(value) # add commas between recip += value # some servers reject [''] fullText = msg.as_string( ) # generate formatted msg # sendmail call raises except if all Tos failed, # or returns failed Tos dict for any that failed print>>sys.stderr,'Sending to...'+ str(recip) #print>>sys.stderr,fullText[:256] server = smtplib.SMTP(self.smtpServerName,timeout=10) #lib.SMTP(self.smtpServerName) # this may fail too #self.getPassword( ) # if srvr requires #self.authenticateServer(server) # login in subclass try: failed = server.sendmail(From, recip, fullText) # except or dict finally: server.quit( ) # iff connect OK if failed: class SomeAddrsFailed(Exception): pass raise SomeAddrsFailed('Failed addrs:%s\n' % failed) #self.saveSentMessage(fullText, saveMailSeparator) print>>sys.stderr,'Send exit'
def send_email(fromAddress, toAddress, subject, message, smtp_server=SMTP_SERVER): """Send an email if there's an error. This will be replaced by sending messages to a log later. """ msg = Message() msg.add_header("To", toAddress) msg.add_header("From", fromAddress) msg.add_header("Subject", subject) msg.set_payload(message) smtp = smtplib.SMTP(smtp_server) smtp.sendmail(fromAddress, [toAddress], msg.as_string()) smtp.quit()
def send_email(fromAddress, toAddress, subject, message): '''Send an email if there's an error. This will be replaced by sending messages to a log later. ''' msg = Message() msg.add_header('To', toAddress) msg.add_header('From', fromAddress) msg.add_header('Subject', subject) msg.set_payload(message) smtp = smtplib.SMTP('bastion') smtp.sendmail(fromAddress, [toAddress], msg.as_string()) smtp.quit()
def send_email(fromAddress, toAddress, subject, message, smtp_server=SMTP_SERVER): '''Send an email if there's an error. This will be replaced by sending messages to a log later. ''' msg = Message() msg.add_header('To', toAddress) msg.add_header('From', fromAddress) msg.add_header('Subject', subject) msg.set_payload(message) smtp = smtplib.SMTP(smtp_server) smtp.sendmail(fromAddress, [toAddress], msg.as_string()) smtp.quit()
def construct_message(imap, msg_format, msg_to, msg_from, msg_date, msg_subject, msg_body): msg = Message() msg.add_header('Date', formatdate(time.mktime(msg_date.timetuple()))) msg.add_header('Message-Id', create_id(msg_date, msg_from)) msg.add_header('To', msg_to) msg.add_header('From', msg_from) msg.add_header('MIME-Version', '1.0') msg.add_header('Subject', msg_subject) payload = Message() payload.add_header('Content-Type', msg_format) if msg_format in ('text/html', 'text/plain'): payload.add_header('Content-Transfer-Encoding', '8bit') payload.set_payload(''.join(msg_body)) else: payload.add_header('Content-Transfer-Encoding', 'base64') payload.add_header('Content-Disposition', 'attachment; filename="%s"' % msg_subject) payload.set_payload(encodestring(''.join(msg_body)).decode()) for item in payload.items(): msg.add_header(item[0], item[1]) msg.set_payload(payload.get_payload()) try: msg.as_string() except Exception, e: print e
def sendgmail(mess): try: server = smtplib.SMTP('smtp.gmail.com') server.starttls() server.login(mygmail,passwd) message = Message() message['Subject'] = 'Sudo小说更新' #邮件标题 message['From'] = mygmail message['To'] = mygmail message.set_payload(mess.encode('utf-8')) msg = message.as_string() server.sendmail(mygmail,mygmail,msg) time.sleep(3) server.quit() except: print "Error"
def send_mail(sender, to, subject, body): glob_email = config.get('global_email_override') if glob_email: to = glob_email message = Message() message["To"] = to message["From"] = sender message["Subject"] = subject message.set_payload(body.encode('utf-8')) server = open_server() try: server.sendmail(sender, to, message.as_string()) warn("mail sent successfully to %s" % to) except smtplib.SMTPRecipientsRefused, e: from pprint import pformat warn("%r: unable to send mail to %s" % (pformat(e.recipients), to))
def main(args): msg1 = Message() msg1.set_charset('iso-2022-jp') msg1['From'] = Header(u'Yusuke Shinyama <*****@*****.**>', 'iso-2022-jp') msg1['To'] = Header(u'きょうから明日です <today@tomorrow>', 'iso-2022-jp') msg1['Subject'] = Header(u'ムーミン谷のみなさんへ', 'iso-2022-jp') msg1['Date'] = 'Thu, 31 Aug 2004 03:06:09 +0900' msg1.set_payload(u'その逆だ!'.encode('iso-2022-jp'), 'iso-2022-jp') fp = file(args.pop(0), 'wb') fp.write(msg1.as_string(0)) fp.close() msg2 = MIMEMultipart() msg2.set_charset('utf-8') msg2['From'] = Header(u'えうすけ <*****@*****.**>', 'iso-2022-jp') msg2['To'] = Header(u'だれでも <any@one>', 'utf-8') msg2['Subject'] = Header(u'何を見てるんだい?', 'iso-2022-jp') msg2['Date'] = 'Thu, 29 Feb 2004 19:23:34 +0500' text1 = MIMEText(u'ああそうか、\nこれは夢なんだ。'.encode('utf-8'), 'plain', 'utf-8') text2 = MIMEText(u'<html><body>\n<strong>HEY!</strong>\n<p>do you wanna feel unconfortably energetic?\n</body></html>', 'html') h = Header(u'ふうばあ ばず', 'iso-2022-jp') text2.add_header('Content-Disposition', 'attachment', filename=h.encode()) msg2.set_payload([text1, text2]) fp = file(args.pop(0), 'wb') fp.write(msg2.as_string(0)) fp.close() msg3 = MIMEMultipart() msg3['From'] = '=?iso-2022-jp?b?Gy?= \xff\xaa\x88' msg3['Subject'] = 'huh?' msg3['Date'] = 'Tue, 25 Nov 2008 01:00:09 +0900' parts = MIMEMultipart() parts.set_payload([MIMEText('part1'), MIMEText('part2')]) msg4 = Message() msg4.set_charset('iso-2022-jp') msg4['From'] = Header(u'john doe <*****@*****.**>', 'iso-2022-jp') msg4['To'] = Header(u'どこだって? <where@where>', 'iso-2022-jp') msg4['Subject'] = Header(u'その先の日本へ', 'iso-2022-jp') msg4['Date'] = 'Sun, 31 Aug 2008 12:20:33 +0900' msg4.set_payload(u'ししかばう゛ー'.encode('iso-2022-jp'), 'iso-2022-jp') msg3.set_payload([parts, MIMEMessage(msg4)]) fp = file(args.pop(0), 'wb') fp.write(msg3.as_string(0)) fp.close() return
def __call__(self, sender, recipient, subject, body): msg = Message() msg.add_header("Subject", subject) msg.add_header("To", str(recipient)) msg.add_header("From", str(sender)) msg.set_payload(body) command = [ self.SENDMAIL_PATH, '-i', '-f', sender.address, recipient.address ] command = Command(command) command.tochild.write(msg.as_string()) command.tochild.close() command.wait() if command.exitcode != 0: raise Error("sendmail failed (%d): %s" % (command.exitcode, command.output))
def send_an_email(self): '''function to send an email. uses self.email_subject, self.email_message and self.email_priority''' #create message object m = Message() #set priority m['X-Priority'] = str(self.email_priority) #set subject m['Subject'] = self.email_subject #set body m.set_payload(self.email_message) # server details server = smtplib.SMTP(host=host, port=port, timeout=10) server.set_debuglevel(1) # verbosity server.starttls() server.ehlo() server.login(user, pw) server.sendmail(me, you, m.as_string())
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 sendMail(config, value): notify_email = config.get("notify","email") smtp_host = config.get("smtp","host") smtp_port = config.get("smtp","port") smtp_user = config.get("smtp","user") smtp_pass = config.get("smtp","pass") hostname = os.uname()[1] m = Message() m['From'] = 'me' m['bcc'] = notify_email m['Subject'] = 'IP Address for ' + hostname + ' is now ' + value server = smtplib.SMTP(smtp_host,smtp_port) server.starttls() server.login(smtp_user,smtp_pass) server.sendmail(smtp_user, notify_email, m.as_string()) server.quit()
def send_warning(val): try: #set values for email sender = SENDER receiver = RECEIVER #set SMTP information server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(sender, "#password") #dummy messages subject = "Warning" text = "Please check the room humidity and temperature!" #Set subject if val == 0: subject = "Temperature risen above %d C!" % MAX_TEMP text = "Warning the temperature has increased above %d" % MAX_TEMP elif val == 1: subject = "Humdity risen above %d percent!" % MAX_HUMIDITY text = "Warning the humidity has increased above %d" % MAX_HUMIDITY #Create an email format from email.Message import Message m = Message() m['X-Priority'] = '2' #set high importance m['Subject'] = subject m.set_payload(text) #Send email server.sendmail(sender, receiver, m.as_string()) #display success on terminal print("Warning sent") except Exception, ex: #Print execptions if any print(ex)
def send(subject, content, to, ssl=0): smtp = 'smtp.qq.com' mail_addr = '*****@*****.**' password = '******' loginuser = mail_addr msg = Message() msg['From'] = mail_addr msg['Subject'] = subject if isinstance(to,str): msg['To'] = to else: msg['To'] = ', '.join(to) if ssl == 1: sm = smtplib.SMTP_SSL() else: sm = smtplib.SMTP() sm.connect(smtp) sm.ehlo() sm.login(loginuser,password) sm.sendmail(mail_addr,to,msg.as_string()+content) sm.close()
def send(subject, content, to, ssl=0): smtp = 'smtp.qq.com' mail_addr = '*****@*****.**' password = '******' loginuser = mail_addr msg = Message() msg['From'] = mail_addr msg['Subject'] = subject if isinstance(to, str): msg['To'] = to else: msg['To'] = ', '.join(to) if ssl == 1: sm = smtplib.SMTP_SSL() else: sm = smtplib.SMTP() sm.connect(smtp) sm.ehlo() sm.login(loginuser, password) sm.sendmail(mail_addr, to, msg.as_string() + content) sm.close()
def forgot_password_view(context, request): email = request.params.get('email', '') message = '' if 'form.submitted' in request.params: schema = ForgotPasswordSchema() try: schema.to_python(request.params) except formencode.validators.Invalid, why: message = str(why) else: profiles = find_profiles(context) found_profile = None for profile in profiles.values(): if profile.email == email: found_profile = profile break if found_profile is None: message = 'Email %s not found' % email else: login = profile.__name__ password = random_password() users = find_users(context) users.change_password(login, password) msg = Message() frm = 'bfg.repoze.org <*****@*****.**>' msg['From'] = frm msg['To'] = email msg['Subject'] = 'Account information' body = 'Your new password is "%s" for login name "%s"' % ( password, login) msg.set_payload(body) msg.set_type('text/html') message = msg.as_string() mailer = get_mailer() mailer.send(frm, [email], message) message = 'Mail sent to "%s" with new password' % email
def main(): """ main subroutine """ (options, path) = parse_args() uri = "file://%s" % path logger = get_logger() repos_name = os.path.basename(uri) config = get_config(options.config, repos_name) client = pysvn.Client() revision = pysvn.Revision(pysvn.opt_revision_kind.number, options.rev) previous = pysvn.Revision(pysvn.opt_revision_kind.number, int(options.rev) - 1) changes = client.diff_summarize(uri, revision1=previous, revision2=revision) # parse log message log = client.log(uri, revision_end=revision)[0] logger.info("Examining commit %s by %s" % (options.rev, log.author)) (message, keywords) = parse_log_message(log.message) summary = build_summary(changes) diffs = dict(diff=[], large=[], binary=[], sensitive=[]) for change in changes: (dtype, ddata) = get_diff_set(change, uri, rev=int(options.rev), largediff=int(config.get(repos_name, 'largediff'))) if dtype is not None: diffs[dtype].append(ddata) # construct the email body = [message.strip(), '', "Author: %s" % log.author, "Revision: %s" % options.rev, '', "Affected files:", ''] for ctype in summary: body.extend(["%-65s %-10s" % (f, ctype) for f in summary[ctype]]) body.append('') if diffs['binary']: body.extend([SEPARATOR, '', "The following binary files were changed:", '']) body.extend(diffs['binary']) body.append('') if diffs['large']: body.extend([SEPARATOR, '', "Diffs for the following files were too large to include:", '']) body.extend(diffs['large']) body.append('') if diffs['sensitive']: body.extend([SEPARATOR, '', "The following sensitive files were changed:", '']) body.extend(diffs['sensitive']) body.append('') if diffs['diff']: body.extend([SEPARATOR, '', "The following files were changed:", '']) body.extend(diffs['diff']) if keywords['resolve']: body.extend(['', "RT-AddRefersTo: %s" % keywords['resolve'], "RT-AddReferredToBy: %s" % keywords['resolve'], "RT-ResolveTicket: %s" % keywords['resolve']]) if config.has_option(repos_name, 'email') and not options.stdout: msg = Message() msg.set_payload("\n".join(body)) subject = None if keywords['subject']: subject = keywords['subject'] elif "\n" in message: subject = message[0:max(120, message.index("\n"))] else: subject = message[0:120] msg['Subject'] = "%s %s" % (config.get(repos_name, 'subject'), subject) msg['From'] = get_author_email(log.author) msg['To'] = config.get(repos_name, 'email') logger.debug("Sending message from %s to %s: %s" % (msg['From'], msg['To'], msg['Subject'])) smtp = smtplib.SMTP('localhost') if options.verbose > 2: # this is _really_ verbose smtp.set_debuglevel(options.verbose - 1) smtp.sendmail(msg['From'], [msg['To']], msg.as_string()) smtp.quit() else: print("\n".join(body))
import socket import time from netifaces import interfaces, ifaddresses, AF_INET smtpserver = '' username = '' password = '' from_addr = '' to_addr = '' message = Message() message['Subject'] = 'IP' message['From'] = from_addr message['To'] = to_addr str_ip_addr = socket.gethostname() + '\n' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + '\n' for ifaceName in interfaces(): addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )] str_ip_addr += ifaceName + ': ' + ', '.join(addresses) + '\n' message.set_payload(str_ip_addr) msg = message.as_string() sm = smtplib.SMTP(smtpserver, port=587, timeout=20) #sm.set_debuglevel(1) sm.ehlo() sm.starttls() sm.ehlo() sm.login(username, password) sm.sendmail(from_addr, to_addr, msg) sm.quit()
msg.set_charset(mailEncoding) msg.set_payload(msgBody.decode(documentEncoding).encode(mailEncoding)) msg['X-User-Agent'] = 'Python Community Server' msg['From'] = '%s (%s)' % ( fromEmail, quoteHeader(fromName, documentEncoding, mailEncoding) ) msg['To'] = u.email msg['Subject'] = quoteHeader(subject, documentEncoding, mailEncoding) try: sender = smtplib.SMTP( "localhost", 25 ) sender.sendmail( set.ServerMailTo(), u.email, msg.as_string(), ) except socket.error, e: err = e except smtplib.SMTPRecipientsRefused: err = _("The recipient's mail server didn't like it.") except smtplib.SMTPHeloError: err = _("The server didn't reply properly to the \"HELO\" greeting!") except smtplib.SMTPSenderRefused: err = _("The server didn't accept the from address!") except smtplib.SMTPDataError:
self.package.version, self.dist, self.arch) msg['X-Rebuildd-Version'] = __version__ msg['X-Rebuildd-Host'] = socket.getfqdn() msg.set_payload(log) try: smtp = smtplib.SMTP() smtp.connect(RebuilddConfig().get('mail', 'smtp_host'), RebuilddConfig().get('mail', 'smtp_port')) smtp.sendmail(RebuilddConfig().get('mail', 'from'), [m.strip() for m in msg['To'].split(",")], msg.as_string()) except Exception, error: try: process = Popen("sendmail", shell=True, stdin=PIPE) process.communicate(input=msg.as_string()) except: RebuilddLog.error("Unable to send build log mail for job %d: %s" % (self.id, error)) return True def __str__(self): return "I: Job %s for %s_%s is status %s on %s for %s/%s" % \ (self.id, self.package.name, self.package.version, self.host, JobStatus.whatis(self.status), self.dist, self.arch) def is_allowed_to_build(self):
Note: this message is being generated by an automated script. You'll continue getting this message until the problem is resolved. Sorry for the inconvenience. Thank you, The Fedora Account System %(admin_email)s ''' % {'name': person.person.human_name, 'email': person.email, 'admin_email': ADMINEMAIL} msg.add_header('To', person.email) msg.add_header('From', ADMINEMAIL) msg.add_header('Subject', 'Fedora Account System and Bugzilla Mismatch') msg.set_payload(message) smtp = smtplib.SMTP(MAILSERVER) smtp.sendmail(ADMINEMAIL, [person.email], msg.as_string()) smtp.quit() recipients = [e for e in NOTIFYEMAIL if e != '$USER'] if recipients and no_bz_account: smtplib.SMTP(MAILSERVER) msg = Message() people = [] for person in no_bz_account: if person.person.status == 'Active': people.append(' %(user)s -- %(name)s -- %(email)s' % {'name': person.person.human_name, 'email': person.email, 'user': person.person.username}) if people: people = '\n'.join(people) message = ''' The following people are in the packager group but do not have email addresses
import smtplib from email.Message import Message mail_server = 'smtp.163.com' mail_server_port = 25 from_addr = '*****@*****.**' to_addr = '*****@*****.**' from_header = 'From: %s\r\n' % from_addr to_header = 'To: %s \r\n ' % to_addr subject_header = 'Subject: nothing intersting' body = 'This is a not-very-intersting email.' email_message = '%s\n%s%s\n\n%s' % (subject_header,from_header,to_header,body) msg = Message() msg['Subject'] = 'subject' msg['From'] = from_addr msg['To'] = to_addr msg.set_payload('mail content') msg = msg.as_string() s = smtplib.SMTP(mail_server,mail_server_port) s.set_debuglevel(1) s.starttls() s.login("*****@*****.**","password") #s.sendmail(from_addr,to_addr,email_message) s.sendmail(from_addr,to_addr,msg) s.quit()
def sendmail(request, to, subject, text, mail_from=None): """ Create and send a text/plain message Return a tuple of success or error indicator and message. @param request: the request object @param to: recipients (list) @param subject: subject of email (unicode) @param text: email body text (unicode) @param mail_from: override default mail_from @type mail_from: unicode @rtype: tuple @return: (is_ok, Description of error or OK message) """ import smtplib, socket from email.Message import Message from email.Charset import Charset, QP from email.Utils import formatdate, make_msgid _ = request.getText cfg = request.cfg mail_from = mail_from or cfg.mail_from logging.debug("send mail, from: %r, subj: %r" % (mail_from, subject)) logging.debug("send mail, to: %r" % (to, )) if not to: return (1, _("No recipients, nothing to do")) subject = subject.encode(config.charset) # Create a text/plain body using CRLF (see RFC2822) text = text.replace(u'\n', u'\r\n') text = text.encode(config.charset) # Create a message using config.charset and quoted printable # encoding, which should be supported better by mail clients. # TODO: check if its really works better for major mail clients msg = Message() charset = Charset(config.charset) charset.header_encoding = QP charset.body_encoding = QP msg.set_charset(charset) # work around a bug in python 2.4.3 and above: msg.set_payload('=') if msg.as_string().endswith('='): text = charset.body_encode(text) msg.set_payload(text) # Create message headers # Don't expose emails addreses of the other subscribers, instead we # use the same mail_from, e.g. u"Jürgen Wiki <*****@*****.**>" address = encodeAddress(mail_from, charset) msg['From'] = address msg['To'] = address msg['Date'] = formatdate() msg['Message-ID'] = make_msgid() msg['Subject'] = Header(subject, charset) # See RFC 3834 section 5: msg['Auto-Submitted'] = 'auto-generated' if cfg.mail_sendmail: # Set the BCC. This will be stripped later by sendmail. msg['BCC'] = ','.join(to) # Set Return-Path so that it isn't set (generally incorrectly) for us. msg['Return-Path'] = address # Send the message if not cfg.mail_sendmail: try: logging.debug("trying to send mail (smtp) via smtp server '%s'" % cfg.mail_smarthost) host, port = (cfg.mail_smarthost + ':25').split(':')[:2] server = smtplib.SMTP(host, int(port)) try: #server.set_debuglevel(1) if cfg.mail_login: user, pwd = cfg.mail_login.split() try: # try to do tls server.ehlo() if server.has_extn('starttls'): server.starttls() server.ehlo() logging.debug( "tls connection to smtp server established") except: logging.debug( "could not establish a tls connection to smtp server, continuing without tls" ) logging.debug( "trying to log in to smtp server using account '%s'" % user) server.login(user, pwd) server.sendmail(mail_from, to, msg.as_string()) finally: try: server.quit() except AttributeError: # in case the connection failed, SMTP has no "sock" attribute pass except UnicodeError, e: logging.exception("unicode error [%r -> %r]" % ( mail_from, to, )) return (0, str(e)) except smtplib.SMTPException, e: logging.exception("smtp mail failed with an exception.") return (0, str(e))
from email.Header import Header from email.Message import Message import fqterm,sys,string lp=long(sys.argv[0]) article=fqterm.getArticle(lp, 100)[0] from_addr = "*****@*****.**" to_addr="*****@*****.**" subject = article.split("\n") subject = subject[1] subject = subject[7:] mess = Message() h = Header(subject,'GB2312') mess['Subject']=h msg = ("Content-Type: text/plain; charset= GB2312\r\n" "From: %s\r\nTo: %s\r\n%s\r\n\r\n" % (from_addr,to_addr, mess.as_string())) msg = msg + article smtp_host = "smtp.email.com" server = smtplib.SMTP(smtp_host) server.set_debuglevel(1) #maybe your smtp need auth #server.login(usr,pwd) server.sendmail(from_addr,to_addr,msg) server.quit()
def sendmail(request, to, subject, text, mail_from=None): """ Create and send a text/plain message Return a tuple of success or error indicator and message. @param request: the request object @param to: recipients (list) @param subject: subject of email (unicode) @param text: email body text (unicode) @param mail_from: override default mail_from @type mail_from: unicode @rtype: tuple @return: (is_ok, Description of error or OK message) """ import smtplib, socket from email.Message import Message from email.Charset import Charset, QP from email.Utils import formatdate, make_msgid _ = request.getText cfg = request.cfg mail_from = mail_from or cfg.mail_from subject = subject.encode(config.charset) # Create a text/plain body using CRLF (see RFC2822) text = text.replace(u'\n', u'\r\n') text = text.encode(config.charset) # Create a message using config.charset and quoted printable # encoding, which should be supported better by mail clients. # TODO: check if its really works better for major mail clients msg = Message() charset = Charset(config.charset) charset.header_encoding = QP charset.body_encoding = QP msg.set_charset(charset) # work around a bug in python 2.4.3 and above: msg.set_payload('=') if msg.as_string().endswith('='): text = charset.body_encode(text) msg.set_payload(text) # Create message headers # Don't expose emails addreses of the other subscribers, instead we # use the same mail_from, e.g. u"Jürgen Wiki <*****@*****.**>" address = encodeAddress(mail_from, charset) msg['From'] = address msg['To'] = address msg['Date'] = formatdate() msg['Message-ID'] = make_msgid() msg['Subject'] = Header(subject, charset) if cfg.mail_sendmail: # Set the BCC. This will be stripped later by sendmail. msg['BCC'] = ','.join(to) # Set Return-Path so that it isn't set (generally incorrectly) for us. msg['Return-Path'] = address # Send the message if not cfg.mail_sendmail: try: logging.debug("trying to send mail (smtp) via smtp server '%s'" % cfg.mail_smarthost) host, port = (cfg.mail_smarthost + ':25').split(':')[:2] server = smtplib.SMTP(host, int(port)) try: #server.set_debuglevel(1) if cfg.mail_login: user, pwd = cfg.mail_login.split() try: # try to do tls server.ehlo() if server.has_extn('starttls'): server.starttls() server.ehlo() logging.debug("tls connection to smtp server established") except: logging.debug("could not establish a tls connection to smtp server, continuing without tls") logging.debug("trying to log in to smtp server using account '%s'" % user) server.login(user, pwd) server.sendmail(mail_from, to, msg.as_string()) finally: try: server.quit() except AttributeError: # in case the connection failed, SMTP has no "sock" attribute pass except smtplib.SMTPException, e: logging.exception("smtp mail failed with an exception.") return (0, str(e)) except (os.error, socket.error), e: logging.exception("smtp mail failed with an exception.") return (0, _("Connection to mailserver '%(server)s' failed: %(reason)s") % { 'server': cfg.mail_smarthost, 'reason': str(e) })
class SmartMessage: """Uproszczony interfejs dla bibliotek Pythona, który potrafi tworzyæ wiadomoœci tekstowe i z za³¹cznikami MIME.""" def __init__(self, fromAddr, toAddrs, subject, body, enc='iso-8859-2'): """Zacznij od za³o¿enia, i¿ bêdzie to prosta wiadomoœæ tekstowa zgodna z RFC 2822 i bez MIME.""" self.msg = Message() self.msg.set_payload(body) self['Subject'] = subject self.setFrom(fromAddr) self.setTo(toAddrs) self.hasAttachments = False self.enc = enc def setFrom(self, fromAddr): "Ustawia adres nadawcy wiadomoœci." if not fromAddr or not type(fromAddr) == type(''): raise Exception, 'Wiadomoœæ musi mieæ jednego i tylko jednego nadawcê.' self['From'] = fromAddr def setTo(self, to): "Ustawia adresy osób, które maj¹ otrzymaæ wiadomoœæ." if not to: raise Exception, 'Wiadomoœæ musi mieæ co najmniej jednego odbiorcê.' self._addresses(to, 'To') #Dodatkowo przechowuj adresy jako listê. Byæ mo¿e #skorzysta z niej kod, który zajmie siê wysy³aniem wiadomoœci. self.to = to def setCc(self, cc): """Ustawia adresy osób, które maj¹ otrzymaæ kopiê wiadomoœc. choæ nie jest ona adresowana do nich w sposób bezpoœredni.""" self._addresses(cc, 'Cc') def addAttachment(self, attachment, filename, mimetype=None): "Do³¹cza do wiadomoœci wskazany plik." #Odgadnij g³ówny i dodatkowy typ MIME na podstawie nazwy pliku. if not mimetype: mimetype = mimetypes.guess_type(filename)[0] if not mimetype: raise Exception, "Nie uda³o siê okreœliæ typu MIME dla", filename if '/' in mimetype: major, minor = mimetype.split('/') else: major = mimetype minor = None #Wiadomoœæ by³a konstruowana z za³o¿eniem, i¿ bêdzie zawieraæ #tylko i wy³¹cznie tekst. Poniewa¿ wiem, ¿e bêdzie zawieraæ #co najmniej jeden za³¹cznik, musimy zmieniæ j¹ na wiadomoœæ #wieloczêœciow¹ i wkleiæ tekst jako pierwsz¹ czêœæ. if not self.hasAttachments: body = self.msg.get_payload() newMsg = MIMEMultipart() newMsg.attach(MIMEText(body, 'plain', self.enc)) #Skopiuj stare nag³ówki do nowego obiektu. for header, value in self.msg.items(): newMsg[header] = value self.msg = newMsg self.hasAttachments = True subMessage = MIMENonMultipart(major, minor, name=filename) subMessage.set_payload(attachment) #Zakoduj teksty jako quoted printable natomiast wszystkie #inne typy jako base64. if major == 'text': encoder = Encoders.encode_quopri else: encoder = Encoders.encode_base64 encoder(subMessage) #Powi¹¿ fragment MIME z g³ówn¹ wiadomoœci¹. self.msg.attach(subMessage) def _addresses(self, addresses, key): """Ustawia zawartoœæ nag³ówka na podstawie listy przekazanych adresów.""" if hasattr(addresses, '__iter__'): addresses = ', '.join(addresses) self[key] = addresses #Kilka metod dodatkowych umo¿liwiaj¹cych traktowanie klasy w podobny #sposób, jak klasy Message lub MultipartMessage, stosuj¹c odpowiedni¹ #delegacjê poleceñ do tych klas. def __getitem__(self, key): "Zwróæ nag³ówek o podanym kluczu." return self.msg[key] def __setitem__(self, key, value): "Ustaw nag³ówek o wskazanej nazwie." self.msg[key] = value def __getattr__(self, key): return getattr(self.msg, key) def __str__(self): "Zwróæ tekstow¹ reprezentacjê wiadomoœci." return self.msg.as_string()