本文整理汇总了Python中smtplib.SMTP.starttls方法的典型用法代码示例。如果您正苦于以下问题:Python SMTP.starttls方法的具体用法?Python SMTP.starttls怎么用?Python SMTP.starttls使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类smtplib.SMTP
的用法示例。
在下文中一共展示了SMTP.starttls方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: send_change_password
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import starttls [as 别名]
def send_change_password(logged_user):
gmail_sender = gmail_config.get_email()
gmail_passwd = gmail_config.get_password()
random_reset_code = hash_string(generate_random_reset_code())
server = SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(gmail_sender, gmail_passwd)
TO = logged_user.get_email()
SUBJECT = 'Password Reset'
TEXT = 'You have requested to change your password. Here is your verification_code:\n' + random_reset_code
BODY = '\r\n'.join([
'To: %s' % TO,
'From: %s' % "[email protected]",
'Subject: %s' % SUBJECT,
'', TEXT
])
try:
server.sendmail("[email protected]", [TO], BODY)
insert_reset_code(logged_user.get_id(), random_reset_code)
print ('An email with a verification code has been sent.')
except:
print ("Error sending mail.")
server.quit()
示例2: MessageSender
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import starttls [as 别名]
class MessageSender(Thread):
def __init__(self, wrappers):
super().__init__()
self.wrappers = wrappers
def run(self):
self._open_server()
for wrapper in self.wrappers:
self._send_message(wrapper.addresses, wrapper.message)
self.server.close()
def _send_message(self, addresses, message):
try:
self.server.sendmail(email_sender.email_address, addresses, message)
except SMTPHeloError:
log.exception("Helo error sending email")
except SMTPRecipientsRefused:
log.warn("Failed to send email to {}".format(addresses))
except SMTPSenderRefused:
log.warn("Sender refused for email")
except SMTPDataError as exp:
log.exception("Unexpected Data error sending email")
def _open_server(self):
self.server = SMTP("smtp.gmail.com", 587)
self.server.ehlo()
self.server.starttls()
self.server.login(email_sender.email_address, email_sender.email_password)
示例3: _plain_send_mail
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import starttls [as 别名]
def _plain_send_mail(sender, recipient, subject, body):
header_charset = 'ISO-8859-1'
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(config.get('registration.smtp_host', 'localhost'))
if config.get('registration.smtp_login'):
try:
smtp.starttls()
except:
pass
smtp.login(config.get('registration.smtp_login'), config.get('registration.smtp_passwd'))
smtp.sendmail(sender, recipient, msg.as_string())
smtp.quit()
示例4: generate_email_alerter
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import starttls [as 别名]
def generate_email_alerter(to_addrs, from_addr=None, use_gmail=False,
username=None, password=None, hostname=None, port=25):
if not from_addr:
from_addr = getuser() + "@" + gethostname()
if use_gmail:
if username and password:
server = SMTP('smtp.gmail.com', 587)
server.starttls()
else:
raise OptionValueError('You must provide a username and password to use GMail')
else:
if hostname:
server = SMTP(hostname, port)
else:
server = SMTP()
server.connect()
if username and password:
server.login(username, password)
def email_alerter(message, subject='SiteWatcher: You have an alert!'):
server.sendmail(from_addr, to_addrs, 'To: %s\r\nFrom: %s\r\nSubject: %s\r\n\r\n%s' % (", ".join(to_addrs), from_addr, subject, message))
return email_alerter, server.quit
示例5: Connectsmtp
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import starttls [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()
示例6: sendEmail
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import starttls [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)
示例7: run
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import starttls [as 别名]
def run(self):
# Serialize/flatten the message
fp = StringIO()
g = Generator(fp, mangle_from_=False)
g.flatten(self.msg)
contents = fp.getvalue()
for rcpt in self.rcpts:
rcpt = utils.find_address(rcpt)
smtp_server = self.MXLookup(rcpt)
conn = SMTP(smtp_server, timeout=30)
conn.set_debuglevel(True)
try:
conn.ehlo()
# FIXME: we should support an option to refuse to send messages
# if the server doesn't support STARTTLS.
if conn.has_extn('starttls'):
conn.starttls()
conn.ehlo()
# TODO: should catch exceptions here and either retry later or
# send a delivery report back to the author.
conn.sendmail(self.from_, rcpt, contents)
finally:
conn.close()
示例8: __init__
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import starttls [as 别名]
class Email:
def __init__( self, name, psw ):
self.name = name
self.psw = psw
self.to = raw_input('To : ')
self.subject = 'Subject : %s\n' % raw_input('Subject : ')
self.msg = raw_input('Msg : ')
self.failed = {}
def __str__( self ):
return 'From : ' + self.name + '\nTo : ' + \
str(self.to) + '\n' + self.subject + '\nBody : ' + self.msg
def __start_server( self ):
if SSL:
self.server = SMTP_SSL( SERVER, PORT )
else:
self.server = SMTP( SERVER, PORT )
self.server.ehlo()
self.server.starttls()
self.server.ehlo()
def send( self ):
self.__start_server()
try:
self.server.login( self.name, self.psw )
except SMTPAuthenticationError:
print('Wrong user or psw')
sys.exit(0)
else:
self.failed = self.server.sendmail( self.name, self.to,
self.subject + self.msg )
self.server.close()
示例9: EmailNotifier
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import starttls [as 别名]
class EmailNotifier(BaseNotifier):
regex = re.compile('^(?:mailto:)?([^:@\s][email protected][^:@\s]+)$')
def __init__(self, config):
self.config = config
self.smtp = SMTP(config['smtp_server'])
context = ssl.create_default_context()
self.smtp.starttls(context=context)
self.smtp.ehlo()
self.smtp.login(
self.config['smtp_username'],
self.config['smtp_password']
)
def notify(self, contact, node):
receipient = self.regex.match(contact).group(1)
msg = MIMEText(
node.format_infotext(self.config['text']),
_charset='utf-8'
)
msg['Subject'] = '[Nodewatcher] %s offline' % node.name
msg['From'] = self.config['from']
msg['To'] = receipient
self.smtp.send_message(msg)
return True
def quit(self):
self.smtp.quit()
示例10: send_courtbooking_mail
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import starttls [as 别名]
def send_courtbooking_mail(recp, sub):
"""
Send email to recepient about courtbooking attempt
"""
try:
creds = netrc()
login, _, passwd = creds.authenticators(GMAIL_SMTP_HOST)
except (OSError, IOError) as err:
if err.errno != errno.ENOENT:
raise
logging.error("send_courtbooking_email: %s", err)
return
except TypeError as err:
logging.error("send_courtbooking_email: Unable to find host %s in" \
" netrc", GMAIL_SMTP_HOST)
return
if login is None or passwd is None:
logging.error("send_courtbooking_mail: Unable to get login and password "
"from netrc")
return
smtp = SMTP(GMAIL_SMTP_HOST, GMAIL_SMTP_PORT)
smtp.starttls()
smtp.login(login, passwd)
headers = "\r\n".join(["from: " + login,
"to: " + recp,
"subject: " + sub,
"mime-version: 1.0",
"content-type: text/plain"])
mail = headers
smtp.sendmail(login, recp, mail)
smtp.quit()
示例11: email
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import starttls [as 别名]
def email(results, host, user, password, recipients, addendum=None):
# Build message.
winners = [
'<li style="font-weight: bold; font-style: italic;">{}</li>'
.format(o.name) if o.premium else '<li>{}</li>'.format(o.name)
for o in results
]
message = (
'<p>Voting complete! Here are the results:</p><ul>{}</ul></p>'
.format('\n'.join(winners))
)
if addendum:
message += '<p>{}</p>'.format(addendum)
message = MIMEText(message, 'html')
message['subject'] = 'Vote: Results'
message['to'] = ', '.join(recipients)
# Set up SMTP.
smtp = SMTP(host)
smtp.starttls()
smtp.login(user, password)
# Send message.
smtp.sendmail(user, recipients, message.as_string())
smtp.close()
示例12: send_email
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import starttls [as 别名]
def send_email(content, destination, subject, file):
try:
msg = MIMEMultipart()
msg['Subject']= subject
msg['From'] = sender # some SMTP servers will do this automatically, not all
fp = open(file, 'rb') # Open File name "file"
img = MIMEImage(fp.read()) # Read the file.
fp.close() # Good housekeeping: close the file.
msg.attach(img) # Attach the file to the message.
conn = SMTP(SMTPserver, port = 587, timeout = 60) # timeout is critical here for long term health.
conn.ehlo()
conn.starttls()
conn.ehlo()
conn.login(USERNAME, PASSWORD)
conn.set_debuglevel(1)
try:
conn.sendmail(sender, destination, msg.as_string())
finally:
conn.close()
except Exception as exc:
# Print a message error!
print("Mail failed; %s" % str(exc))
print("Moving on!")
示例13: SendEmail
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import starttls [as 别名]
def SendEmail(subject, msgText, to, user,password, alias, imgName, replyTo=None):
sender = alias
try:
conn = SMTP('smtp.gmail.com', 587)
msg = MIMEMultipart()
msg.attach(MIMEText(msgText, 'html'))
msg['Subject']= subject
msg['From'] = sender
msg['cc'] = to
#msg['cc'] = ', '.join(to)
if replyTo:
msg['reply-to'] = replyTo
if imgName != None:
fp = open(imgName, 'rb')
img = MIMEImage(fp.read(), _subtype="pdf")
fp.close()
img.add_header('Content-Disposition', 'attachment', filename = imgName)
msg.attach(img)
conn.ehlo()
conn.starttls()
conn.set_debuglevel(False)
conn.login(user, password)
try:
conn.sendmail(sender, to, msg.as_string())
finally:
conn.close()
except:
print "Unexpected error:", sys.exc_info()[0]
示例14: email_stuff
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import starttls [as 别名]
def email_stuff(sender_email, recipient, subject, message, files, smtp_server, port_num, smtp_pw):
sender = sender_email
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = recipient
msg['Subject'] = subject
body = message
msg.attach(MIMEText(body, 'plain'))
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="{0}"'.format(path.basename(f)))
msg.attach(part)
server = SMTP(smtp_server, port_num)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.ehlo()
server.login(sender_email, smtp_pw)
msg = msg.as_string()
server.sendmail(sender, recipient, msg)
server.quit()
示例15: send_email
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import starttls [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()