本文整理汇总了Python中smtplib.SMTP类的典型用法代码示例。如果您正苦于以下问题:Python SMTP类的具体用法?Python SMTP怎么用?Python SMTP使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SMTP类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: send_email
def send_email(request):
try:
recipients = request.GET["to"].split(",")
url = request.GET["url"]
proto, server, path, query, frag = urlsplit(url)
if query:
path += "?" + query
conn = HTTPConnection(server)
conn.request("GET", path)
try: # Python 2.7+, use buffering of HTTP responses
resp = conn.getresponse(buffering=True)
except TypeError: # Python 2.6 and older
resp = conn.getresponse()
assert resp.status == 200, "Failed HTTP response %s %s" % (resp.status, resp.reason)
rawData = resp.read()
conn.close()
message = MIMEMultipart()
message["Subject"] = "Graphite Image"
message["To"] = ", ".join(recipients)
message["From"] = "[email protected]%s" % gethostname()
text = MIMEText("Image generated by the following graphite URL at %s\r\n\r\n%s" % (ctime(), url))
image = MIMEImage(rawData)
image.add_header("Content-Disposition", "attachment", filename="composer_" + strftime("%b%d_%I%M%p.png"))
message.attach(text)
message.attach(image)
s = SMTP(settings.SMTP_SERVER)
s.sendmail("[email protected]%s" % gethostname(), recipients, message.as_string())
s.quit()
return HttpResponse("OK")
except:
return HttpResponse(format_exc())
示例2: send_email
def send_email(subject, message, addr):
try:
if (Config.get("smtp", "port") == "0"):
smtp = SMTP("localhost")
else:
smtp = SMTP(Config.get("smtp", "host"), Config.get("smtp", "port"))
if not ((Config.get("smtp", "host") == "localhost") or (Config.get("smtp", "host") == "127.0.0.1")):
try:
smtp.starttls()
except SMTPException as e:
raise SMSError("unable to shift connection into TLS: %s" % (str(e),))
try:
smtp.login(Config.get("smtp", "user"), Config.get("smtp", "pass"))
except SMTPException as e:
raise SMSError("unable to authenticate: %s" % (str(e),))
try:
smtp.sendmail(Config.get("smtp", "frommail"), addr, "To:%s\nFrom:%s\nSubject:%s\n%s\n" % (addr, "\"%s\" <%s>" % (
Config.get("Connection", "nick"), Config.get("smtp", "frommail")), subject, message))
except SMTPSenderRefused as e:
raise SMSError("sender refused: %s" % (str(e),))
except SMTPRecipientsRefused as e:
raise SMSError("unable to send: %s" % (str(e),))
smtp.quit()
except (socket.error, SSLError, SMTPException, SMSError) as e:
return "Error sending message: %s" % (str(e),)
示例3: sendmail
def sendmail(content=None):
"Send email to my 163mail"
if content is None:
print 'content is None'
return False
try:
from smtplib import SMTP
from email.mime.text import MIMEText
from_addr = "[email protected]"
password = "hanks0722"
to_addr = "[email protected]"
email_client = SMTP(host='smtp.163.com')
email_client.login(from_addr, password)
#create message
msg = MIMEText(content, _charset='utf-8')
msg['Subject'] = "Interview Status Changed!"
email_client.sendmail(from_addr, to_addr, msg.as_string())
return True
except Exception, e:
print e
return False
示例4: deliver
def deliver(self, subject, body, recipients=False):
"""
sends an email using the [email protected] account
"""
if not recipients:
recipients = self.recipients
recipients = recipients.split(';')
message = MIMEText(body)
message['Subject'] = subject
message['From'] = self.sender
message['To'] = ','.join(recipients)
if self.testing:
print('***Begin Test Email Message***')
print(message)
print('***End Test Email Message***')
return
s = SMTP(self.server, self.port)
s.sendmail(self.sender, recipients, message.as_string())
s.quit()
print('email sent')
示例5: send_email
def send_email(request):
try:
recipients = request.GET['to'].split(',')
url = request.GET['url']
proto, server, path, query, frag = urlsplit(url)
if query: path += '?' + query
conn = HTTPConnection(server)
conn.request('GET',path)
resp = conn.getresponse()
assert resp.status == 200, "Failed HTTP response %s %s" % (resp.status, resp.reason)
rawData = resp.read()
conn.close()
message = MIMEMultipart()
message['Subject'] = "Graphite Image"
message['To'] = ', '.join(recipients)
message['From'] = '[email protected]%s' % gethostname()
text = MIMEText( "Image generated by the following graphite URL at %s\r\n\r\n%s" % (ctime(),url) )
image = MIMEImage( rawData )
image.add_header('Content-Disposition', 'attachment', filename="composer_" + strftime("%b%d_%I%M%p.png"))
message.attach(text)
message.attach(image)
s = SMTP(settings.SMTP_SERVER)
s.sendmail('[email protected]%s' % gethostname(),recipients,message.as_string())
s.quit()
return HttpResponse( "OK" )
except:
return HttpResponse( format_exc() )
示例6: sendEmail
def sendEmail(self, subject, body, toAddress=False):
"""
sends an email using the [email protected] account
"""
if not toAddress:
toAddress = self.toAddress
toAddress = toAddress.split(";")
message = MIMEText(body)
message["Subject"] = subject
message["From"] = self.fromAddress
message["To"] = ",".join(toAddress)
if not self.testing:
s = SMTP(self.server, self.port)
s.sendmail(self.fromAddress, toAddress, message.as_string())
s.quit()
print("email sent")
else:
print("***Begin Test Email Message***")
print(message)
print("***End Test Email Message***")
示例7: send_email
def send_email(prefs, report_str):
recipients = prefs['ADMIN_EMAIL'].split(',')
msg = dedent("""
From: %s
To: %s
Subject: %s
Date: %s
""").lstrip() % (prefs.get('SMTP_FROM'),
prefs.get('ADMIN_EMAIL'),
prefs.get('SMTP_SUBJECT'),
time.strftime(prefs.get('SMTP_DATE_FORMAT')))
msg += report_str
try:
smtp = SMTP(prefs.get('SMTP_HOST'),
prefs.get('SMTP_PORT'))
username = prefs.get('SMTP_USERNAME')
password = prefs.get('SMTP_PASSWORD')
if username and password:
smtp.login(username, password)
smtp.sendmail(prefs.get('SMTP_FROM'),
recipients,
msg)
debug("sent email to: %s" % prefs.get("ADMIN_EMAIL"))
except Exception, e:
print "Error sending email"
print e
print "Email message follows:"
print msg
示例8: process_message
def process_message(self, message):
"""Send emails.
Args:
message: dict instance containing email info.
Fields:
type [REQUIRED]: HR_ASC / HR_DESC
attachments [OPTIONAL]: recorded images base64 encoded
"""
self.logger.info("Sending email to %s" % RECEIVER)
if not message.get('type'):
self.logger.error('Received message has no type (it should have '
'been one of the following: HR_ASC/HR_DESC): %r')
return
if not message.get('attachments'):
message = self.compose_message_without_attachments(message)
else:
message = self.compose_message_with_attachments(message)
try:
smtpObj = SMTP('localhost')
smtpObj.sendmail(SENDER, RECEIVER, message)
self.logger.info("Successfully sent email to %s", RECEIVER)
except SMTPException as e:
self.logger.error("Unable to send email to %s: %r", RECEIVER, e)
示例9: monitor_score_rank
def monitor_score_rank(self):
"""
监控博客积分及排名的变化
:return:
"""
while True:
self.get_blog_ranks()
if self.score != self.his_score or self.rank != self.his_rank:
email_client = SMTP(host = 'smtp.126.com')
email_client.login('[email protected]','******')
mail_title = '[e-notice]:blog-rank-changes'
# mail_body = "[%s]time-(score,rank):old-(%s,%s),now-(%s,%s)" \
# % (
# self.id,
# self.his_score, self.his_rank,
# self.score, self.rank
# )
msg_body = "%s, at %s, you score: %s, rank: %s" %(self.id, time.ctime(), self.score, self.rank)
msg = MIMEText(msg_body,_charset='utf-8')
msg['Subject'] = mail_title
email_client.sendmail('[email protected]','[email protected]',msg.as_string())
self.his_score = self.score
self.his_rank = self.rank
sleep(self.gap_seconds)
示例10: send_mail
def send_mail(subject, sender, recipient, text, server, files=[]):
"""Sends email with attachment"""
# Create the enclosing (outer) message
outer = MIMEMultipart()
outer['Subject'] = subject
outer['To'] = recipient
outer['From'] = sender
outer.preamble = 'You will not see this in a MIME-aware mail reader.'
msg = MIMEText(text)
outer.attach(msg)
for filename in files:
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
fp = open(filename, 'rb')
msg = MIMEBase(maintype, subtype)
msg.set_payload(fp.read())
fp.close()
# Encode the payload using Base64
encoders.encode_base64(msg)
# Set the filename parameter
msg.add_header('Content-Disposition', 'attachment', filename=filename)
outer.attach(msg)
composed = outer.as_string()
session = SMTP('localhost')
session.sendmail(sender, recipient, composed)
session.quit()
示例11: notify
def notify(self, seminar):
"""
Notify seminar
"""
import re
from datetime import datetime
from smtplib import SMTP
from email.mime.text import MIMEText
from email.header import Header
dt = datetime.combine(seminar.date, seminar.time)
format_values = (seminar.title, '\n'.join([' ' + c for c in seminar.contents]), seminar.place)
datetime_formatter = lambda matches: dt.strftime(matches.group(0))
datetime_pattern = re.compile('%-?[a-zA-Z]')
message_body = datetime_pattern.sub(datetime_formatter, self.message.format(*format_values))
message = MIMEText(message_body, _charset = 'UTF-8')
message['Subject'] = Header(datetime_pattern.sub(datetime_formatter, self.subject.format(*format_values)), 'UTF-8').encode()
message['From'] = self.from_
message['To'] = ', '.join(self.to)
smtp = SMTP(self.host, self.port)
smtp.sendmail(self.from_, self.to, message.as_string())
smtp.quit()
示例12: mailtrn
def mailtrn(trndir,fltid,lognum):
from smtplib import SMTP
from email.mime.text import MIMEText
from socket import gethostname
from getpass import getuser
# Create a text/plain message from file.
trnfile = str.format('{0:s}/{1:s}/ema-{1:s}-log-{2:04d}.trn',trndir,fltid,lognum)
if options.verbose:
print('compute trnfile: ', trnfile)
fp = open(trnfile, 'rt')
msg = MIMEText(fp.read())
fp.close()
# msg = MIMEText('New trnfile: ' + trnfile)
host = gethostname()
user = getuser()
From = '[email protected]'
From = user+'@'+host
To = '[email protected]'
Reply_To = '[email protected]'
msg['Subject'] = str.format('emarun.py {0:s} {1:04d}',fltid,lognum)
msg['From'] = From
msg['To'] = To
msg.add_header('Reply-To', Reply_To)
s = SMTP('localhost')
s.sendmail(From, To, msg.as_string())
s.quit()
示例13: sendMail
def sendMail(rcpt, subject, body, files=[]):
send_from = "[email protected]"
msg = MIMEMultipart()
msg['From'] = send_from
if rcpt is None: rcpt = admin_email
msg['To'] = COMMASPACE.join(rcpt)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach( MIMEText(body) )
for f,b in files:
logger.debug("SEND ATT "+f)
part = MIMEBase('application', "octet-stream")
part.set_payload(open(f).read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(b))
msg.attach(part)
server = SMTP(smtphost, smtpport)
server.sendmail(send_from, rcpt, msg.as_string())
server.close()
示例14: send
def send(self, msg):
if len(msg['text']) > 32:
teaser = msg['text'][:32] + '...'
else:
teaser = msg['text']
msg = '''From: %s
To: %s
Subject: %s
%s''' % (self.config['mail']['from_address'], self.config['mail']['to_address'], '[foobox] %s: %s' % (msg['src'], teaser), msg['text'])
host = self.config['mail']['smtp_server']
if host.rfind(':') != -1:
host, port = host.rsplit(':', 1)
else:
port = 25
port = int(port)
logging.debug('Sending mail via %s:%s' % (host, port))
try:
server = SMTP(host, port)
server.sendmail(self.config['mail']['from_address'], self.config['mail']['to_address'], msg)
server.quit()
logging.info('Sent email to %s' % self.config['mail']['to_address'])
except:
logging.error('Error sending mail: %s' % format_exc())
示例15: response
def response(self, nick, args, kwargs):
try:
sendto, reason = args
email = self.learn.lookup(u'email', sendto)
if email is None:
return u"%s: I don't know the email for %s" % (nick, sendto)
# just make all this shit ASCII, email is best that way...
email = email.encode('ascii', 'replace')
if reason:
reason = reason.encode('ascii', 'replace')
anick = nick.encode('ascii', 'replace')
body = 'To: %s <%s>\n' % (sendto.encode('ascii', 'replace'), email)
body += 'From: %s\n' % (self.config.smtp.sender)
body += 'Subject: Summon from %s' % anick
body += '\n'
body += 'You were summoned by %s. Reason: %s' % (anick, reason)
smtp = SMTP(self.config.smtp.server)
if len(self.config.smtp.user):
smtp.login(self.config.smtp.user, self.config.smtp.password)
smtp.sendmail(self.config.smtp.sender, [email], body)
return u"%s: summoned %s" % (nick, sendto)
except Exception, error:
log.warn(u'error in module %s' % self.__module__)
log.exception(error)
return u"%s: I couldn't make that summon: %s" % (nick, error)