本文整理汇总了Python中smtplib.SMTP.login方法的典型用法代码示例。如果您正苦于以下问题:Python SMTP.login方法的具体用法?Python SMTP.login怎么用?Python SMTP.login使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类smtplib.SMTP
的用法示例。
在下文中一共展示了SMTP.login方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: EmailNotifier
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import login [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()
示例2: send_report_after_ran_test
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import login [as 别名]
def send_report_after_ran_test():
"""根据 config 中的配置信息,在完成测试后通过邮件方式发送 HTML 格式报告给相关人
Args: None.
return: None.
raise: None.
"""
msg = MIMEMultipart()
msg['subject'] = u"软件测试报告"
msg['from'] = config.email_sender
msg['to'] = config.email_reciver
url = "http://" + config.report_server_name + ":" + config.report_server_port + "/report/" \
+ os.path.split(config.report_dir)[1] + '/summary_report.html'
print_debug_info("the report's url is: " + url)
report_content = MIMEText(urllib2.urlopen(url).read().decode('utf-8'), 'html')
msg.attach(report_content)
print_debug_info("report attached.")
try:
smtp = SMTP()
smtp.connect(config.smtp_server_name, config.smtp_server_port)
smtp.login(config.smtp_username, config.smtp_password)
smtp.sendmail(config.email_sender, config.email_reciver, \
msg.as_string())
print_debug_info("report has already sent.")
smtp.quit()
except Exception, e:
raise e
示例3: _plain_send_mail
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import login [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: send_mail
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import login [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 login [as 别名]
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
示例6: might_work
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import login [as 别名]
def might_work(sender, receiver):
server = options.value("smtp_hostname", "localhost")
port = options.value("smtp_port", 25)
username = options.value("smtp_username", "")
password = options.value("smtp_password", "")
my_hostname = socket.getfqdn()
test_commands = [
('EHLO', my_hostname),
('MAIL FROM:', sender),
('RCPT TO:', receiver)
]
try:
server = SMTP(server, int(port))
if username != "" and password != "":
# The .login() function only accepts str, not unicode, so force it
server.login(str(username), str(password))
for cmd, arg in test_commands:
code, msg = server.docmd(cmd, arg)
if code == 250:
continue
raise SendEmailError('SMTP: %s was not accepted: %s' % (cmd, msg))
# do not actually send something
server.quit()
except (SMTPException, socket.error) as e:
raise SendEmailError('SMTP: %s' % (str(e), ))
示例7: Connectsmtp
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import login [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: EmailConnection
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import login [as 别名]
class EmailConnection(object):
def __init__(self, username, password):
self.username = username
self.password = password
self.connect_to_gmail()
def connect_to_gmail(self):
self.connection = SMTP('smtp.gmail.com', 587)
self.connection.starttls()
self.connection.ehlo()
self.connection.login(self.username, self.password)
def send(self, message, to=None, subject=None):
if isinstance(message, basestring):
if to is None or subject is None:
raise ValueError('You need to specify both `to` and `subject`')
else:
message = Email(
from_=self.username,
to=to,
subject=subject,
message=message
)
from_ = message.email['From']
to = message.email['To'].split(',')
if 'Cc' in message.email:
to = to + message.email['Cc'].split(',')
message = str(message)
self.connection.sendmail(from_, to, message)
self.connection.close()
示例9: send_email
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import login [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()
示例10: base_smtp_send
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import login [as 别名]
def base_smtp_send(item):
usetls, smtp_server, mail_from, mail_pwd, name_from, mail_to, name_to, subject, body = item
message = """From: {} <{}>
To: {} <{}>
Subject: {}
{}
""".format(name_from, mail_from, name_to, mail_to, subject, body.replace('\\n','\n'))
temp = smtp_server.split(':')
smtp_host = temp[0]
if usetls:
smtp_port = 587
else:
smtp_port = 465
if len(temp) > 1:
smtp_port = temp[1]
server = SMTP(smtp_server, smtp_port)
if usetls:
server.ehlo()
server.starttls()
server.ehlo
server.login(mail_from, mail_pwd)
server.sendmail(mail_from, mail_to, message)
server.quit()
return True
示例11: run
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import login [as 别名]
def run(self):
sub_header = uniqueid
if self.jobid:
sub_header = 'imp:{}:{}'.format(uniqueid, self.jobid)
elif self.checkin:
sub_header = 'checkin:{}'.format(uniqueid)
msg = MIMEMultipart()
msg['From'] = sub_header
msg['To'] = gmail_user
msg['Subject'] = sub_header
message_content = json.dumps({'fgwindow': detectForgroundWindows(), 'sys': getSysinfo(), 'admin': isAdmin(), 'msg': self.text})
msg.attach(MIMEText(str(message_content)))
for attach in self.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)
while True:
try:
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()
break
except Exception as e:
#if verbose == True: print_exc()
time.sleep(10)
示例12: create_and_send_mail_messages
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import login [as 别名]
def create_and_send_mail_messages(messages):
if not settings.EMAIL_HOST:
return
sender = Header(unicode(settings.APP_SHORT_NAME), 'utf-8')
sender.append('<%s>' % unicode(settings.DEFAULT_FROM_EMAIL))
sender = u'%s <%s>' % (unicode(settings.APP_SHORT_NAME), unicode(settings.DEFAULT_FROM_EMAIL))
try:
connection = SMTP(str(settings.EMAIL_HOST), str(settings.EMAIL_PORT))
"""
connection = SMTP(str(settings.EMAIL_HOST), str(settings.EMAIL_PORT),
local_hostname=DNS_NAME.get_fqdn())
"""
if (bool(settings.EMAIL_USE_TLS)):
connection.ehlo()
connection.starttls()
connection.ehlo()
if settings.EMAIL_HOST_USER and settings.EMAIL_HOST_PASSWORD:
connection.login(str(settings.EMAIL_HOST_USER), str(settings.EMAIL_HOST_PASSWORD))
if sender is None:
sender = str(settings.DEFAULT_FROM_EMAIL)
for recipient, subject, html, text, media in messages:
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = Header(subject, 'utf-8')
msgRoot['From'] = sender
to = Header(recipient.username, 'utf-8')
to.append('<%s>' % recipient.email)
msgRoot['To'] = to
#msgRoot.preamble = 'This is a multi-part message from %s.' % unicode(settings.APP_SHORT_NAME).encode('utf8')
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
msgAlternative.attach(MIMEText(text.encode('utf-8'), _charset='utf-8'))
msgAlternative.attach(MIMEText(html.encode('utf-8'), 'html', _charset='utf-8'))
for alias, location in media.items():
fp = open(location, 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<'+alias+'>')
msgRoot.attach(msgImage)
try:
connection.sendmail(sender, [recipient.email], msgRoot.as_string())
except Exception, e:
logging.error("Couldn't send mail using the sendmail method: %s" % e)
try:
connection.quit()
except socket.sslerror:
connection.close()
示例13: reply_mail
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import login [as 别名]
def reply_mail(mail_obj, is_success=True, body=None):
print "begin to reply email to [%s] " %(mail_obj["From"] or mail_obj["Reply-To"])
original = mail_obj
config = dict(load_config().items("smtp"))
smtp = SMTP()
smtp.connect('smtp.gmail.com', 587)
smtp.starttls()
smtp.login(config["user"], config["pass"])
from_addr = "[email protected]"
to_addr = original["Reply-To"] or parse_base64_mail_mime(original["From"])
subject, encoding = decode_header(original["Subject"])[0]
if encoding:
subject = subject.decode(encoding)
subj = u"Re: " + subject
else:
subj = u"Re: " + subject
date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )
message_text = "Hello\nThis is a mail from your server\n\nBye\n"
if body is not None:
msg = u"From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, body.replace('\\n','\n') )
else:
msg = u"From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, is_success.replace('\\n','\n') )
smtp.sendmail(from_addr, to_addr, unicode(msg))
smtp.quit()
print "replied email to [%s] " %(parse_base64_mail_mime(mail_obj["From"]) or mail_obj["Reply-To"])
示例14: send_verification_email
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import login [as 别名]
def send_verification_email(self):
try:
email = "[email protected]"
from sensitive_data import email_password
password = email_password
except ImportError:
email = "???"
password = "???"
message = ("From: {0}\n"
"To: {1}\n"
"Subject: Piki bids you welcome."
"\n\n"
"Thank you for giving Piki a shot, {2}. "
"I hope you will find it useful."
"\n\n"
"Your verification link is "
"http://piki.heroku.com/verify/{3}/{4}."
"\n\n"
"If you have any questions, or perhaps some feedback, "
"write an email to [email protected]"
).format(email, self.email, self.name, self.name_slug,
self.verification_code())
server = SMTP("smtp.gmail.com:587")
server.ehlo()
server.starttls()
server.login(email, password)
server.sendmail(email, user.email, message)
server.quit()
示例15: generate_email_alerter
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import login [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