本文整理汇总了Python中smtplib.SMTP.sendmail方法的典型用法代码示例。如果您正苦于以下问题:Python SMTP.sendmail方法的具体用法?Python SMTP.sendmail怎么用?Python SMTP.sendmail使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类smtplib.SMTP
的用法示例。
在下文中一共展示了SMTP.sendmail方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: send_email
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import sendmail [as 别名]
def send_email(sender, recipient, subject, body, host='localhost', port='25', username=None, password=None, header_charset='UTF-8'):
for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
try:
body.encode(body_charset)
except UnicodeError:
pass
else:
break
sender_name, sender_addr = parseaddr(sender)
recipient_name, recipient_addr = parseaddr(recipient)
sender_name = str(Header(unicode(sender_name), header_charset))
recipient_name = str(Header(unicode(recipient_name), header_charset))
sender_addr = sender_addr.encode('ascii')
recipient_addr = recipient_addr.encode('ascii')
msg = MIMEText(body.encode(body_charset), 'plain', body_charset)
msg['From'] = formataddr((sender_name, sender_addr))
msg['To'] = formataddr((recipient_name, recipient_addr))
msg['Subject'] = Header(unicode(subject), header_charset)
smtp = SMTP('{host}:{port}'.format(host=host, port=port))
smtp.starttls()
if username and password:
smtp.login(username,password)
smtp.sendmail(sender, recipient, msg.as_string())
smtp.quit()
示例2: _send
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import sendmail [as 别名]
def _send( self, mfrom, mto, messageText ):
""" Send the message """
smtpserver = SMTP(self.smtp_host, int(self.smtp_port) )
if self.smtp_uid:
smtpserver.login(self.smtp_uid, self.smtp_pwd)
smtpserver.sendmail( mfrom, mto, messageText )
smtpserver.quit()
示例3: send_email
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import sendmail [as 别名]
def send_email(sender, recipient, subject, body):
from smtplib import SMTP
from email.MIMEText import MIMEText
from email.Header import Header
from email.Utils import parseaddr, formataddr
# Header class is smart enough to try US-ASCII, then the charset we
# provide, then fall back to UTF-8.
header_charset = 'ISO-8859-1'
# We must choose the body charset manually
for body_charset in 'UTF-8', 'ISO-8859-1', 'US-ASCII' :
try:
body.encode(body_charset)
except UnicodeError:
pass
else:
break
# Split real name (which is optional) and email address parts
sender_name, sender_addr = parseaddr(sender)
recipient_name, recipient_addr = parseaddr(recipient)
# We must always pass Unicode strings to Header, otherwise it will
# use RFC 2047 encoding even on plain ASCII strings.
sender_name = str(Header(unicode(sender_name), header_charset))
recipient_name = str(Header(unicode(recipient_name), header_charset))
# Make sure email addresses do not contain non-ASCII characters
sender_addr = sender_addr.encode('ascii')
recipient_addr = recipient_addr.encode('ascii')
# Create the message ('plain' stands for Content-Type: text/plain)
msg = MIMEText(body.encode(body_charset), 'plain', body_charset)
msg['From'] = formataddr((sender_name, sender_addr))
msg['To'] = formataddr((recipient_name, recipient_addr))
msg['Subject'] = Header(unicode(subject), header_charset)
# Send the message via SMTP to localhost:25
smtp = SMTP("localhost")
smtp.sendmail(sender, recipient, msg.as_string())
smtp.quit()
示例4: send_mail
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import sendmail [as 别名]
def send_mail(send_to, subject, text, files=[], server='localhost',
username=None, password=None):
send_from = '[email protected]'
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(MIMEText(text))
for f in files:
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(f, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % basename(f))
msg.attach(part)
smtp = SMTP(server)
if username is not None:
smtp.login(str(username), str(password))
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()
示例5: sendmail
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import sendmail [as 别名]
def sendmail(self, destination, subject, message, attach = None):
try:
msg = MIMEMultipart()
msg['From'] = self.username
msg['Reply-to'] = self.username
msg['To'] = destination
msg['Subject'] = subject
msg.attach(MIMEText(message))
if attach:
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
mailServer = SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
try:
mailServer.login(self.username, self.password)
mailServer.sendmail(self.username, destination, msg.as_string())
finally:
mailServer.close()
except Exception, exc:
sys.exit("Failed to send mail; %s" % str(exc))
示例6: send_email
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import sendmail [as 别名]
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),)
示例7: Connectsmtp
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import sendmail [as 别名]
class Connectsmtp(object):
"""
"""
fromaddr = "[email protected]"
toaddr = "[email protected]"
username = "[email protected]"
password = "XXXXXXXX"
subject = "DeliverhHero log analysis"
smtpser = "smtp.gmail.com:587"
def __init__(self):
self.smtp = SMTP(self.smtpser)
self.smtp.starttls()
self.smtp.login(self.username, self.password)
def sendit(self, cont, att, attname):
"""
"""
self.msg = mimemultipart()
self.content = mimetext(cont, "plain", "utf-8")
self.msg.attach(self.content)
self.attachment = mimebase('application', 'octet-stream')
self.attachment.set_payload(att)
self.attachment.add_header('Content-Disposition', 'attachment; filename="%s"' % attname)
self.msg.attach(self.attachment)
self.msg["subject"] = self.subject
self.smtp.sendmail(self.fromaddr, self.toaddr, self.msg.as_string())
return True
def __del__(self):
self.smtp.quit()
示例8: send_email
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import sendmail [as 别名]
def send_email(from_, to, cc, subject, content):
"""
@param from_ (str)
@param to (list - str)
@param cc (list - str)
@param content (str)
"""
msg = MIMEText(content, _charset='utf-8')
msg['Subject'] = subject
msg['From'] = from_
assert type(to) is list
assert type(cc) is list
msg['To'] = ",".join(to)
msg['Cc'] = ",".join(cc)
email_is_sent = False
try:
email_server = SMTP('smtp')
try:
email_server.sendmail(from_, to + cc, msg.as_string())
email_is_sent = True
except:
logging.error("*** Failed to send the email")
email_server.quit()
except:
logging.error("*** Can't connect to the SMTP server")
return email_is_sent
示例9: do_run
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import sendmail [as 别名]
def do_run(self):
while True:
try:
cycle = self.cycles.get(timeout=1)
except ConcurrentEmpty:
continue
if not self.server.config.mail.enabled:
log.debug("Mail is disabled")
continue
from_addr = self.server.config.operator
to_addrs = self.server.config.mail.default_recipients
content = self.status_message.render(cycle)
if self.server.debug:
log.debug("Mail message:\n%s", content)
continue
smtp = SMTP()
smtp.connect()
try:
smtp.sendmail(from_addr, to_addrs, content)
finally:
smtp.quit()
示例10: sendEmail
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import sendmail [as 别名]
def sendEmail(self, botid, jobid, cmd, arg='', attachment=[]):
if (botid is None) or (jobid is None):
sys.exit("[-] You must specify a client id (-id) and a jobid (-job-id)")
sub_header = 'gdog:{}:{}'.format(botid, jobid)
msg = MIMEMultipart()
msg['From'] = sub_header
msg['To'] = gmail_user
msg['Subject'] = sub_header
msgtext = json.dumps({'cmd': cmd, 'arg': arg})
msg.attach(MIMEText(str(infoSec.Encrypt(msgtext))))
for attach in attachment:
if os.path.exists(attach) == True:
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(os.path.basename(attach)))
msg.attach(part)
mailServer = SMTP()
mailServer.connect(server, server_port)
mailServer.starttls()
mailServer.login(gmail_user,gmail_pwd)
mailServer.sendmail(gmail_user, gmail_user, msg.as_string())
mailServer.quit()
print "[*] Command sent successfully with jobid: {}".format(jobid)
示例11: sendEmail
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import sendmail [as 别名]
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***")
示例12: send_email
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import sendmail [as 别名]
def send_email(to, subject, content):
"""This method sends an email"""
#Create the message
msg = MIMEMultipart('alternative')
msg = addheader(msg, 'Subject', subject)
msg["Subject"] = subject
msg["From"] = EMAIL_SENDER
msg["To"] = listToStr(to)
content = MIMEText(content.encode('utf-8'), "html")
msg.attach(content);
try:
smtpObj = SMTP(GMAIL_SMTP, GMAIL_SMTP_PORT)
#Identify yourself to GMAIL ESMTP server.
smtpObj.ehlo()
#Put SMTP connection in TLS mode and call ehlo again.
smtpObj.starttls()
smtpObj.ehlo()
#Login to service
smtpObj.login(user=EMAIL_SENDER, password=PASSWORD)
#Send email
print msg.as_string()
smtpObj.sendmail(EMAIL_SENDER, to, msg.as_string())
#close connection and session.
smtpObj.quit();
except SMTPException as error:
print "Error: unable to send email : {err}".format(err=error)
示例13: _send
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import sendmail [as 别名]
def _send( self ):
if not self._mailAddress:
gLogger.warn( "No mail address was provided. Mail not sent." )
return S_ERROR( "No mail address was provided. Mail not sent." )
if not self._message:
gLogger.warn( "Message body is empty" )
if not self._subject:
gLogger.warn( "Subject and body empty. Mail not sent" )
return S_ERROR ( "Subject and body empty. Mail not sent" )
mail = MIMEText( self._message , "plain" )
addresses = self._mailAddress
if not type( self._mailAddress ) == type( [] ):
addresses = [self._mailAddress]
mail[ "Subject" ] = self._subject
mail[ "From" ] = self._fromAddress
mail[ "To" ] = ', '.join( addresses )
smtp = SMTP()
smtp.set_debuglevel( 0 )
try:
smtp.connect()
smtp.sendmail( self._fromAddress, addresses, mail.as_string() )
except Exception, x:
return S_ERROR( "Sending mail failed %s" % str( x ) )
示例14: response
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import sendmail [as 别名]
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)
示例15: send_email
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import sendmail [as 别名]
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() )