def send_email(mail_user, mail_password, mail_recipient, subject, body):
FROM = mail_user
TO = mail_recipient if type(mail_recipient) is list else [mail_recipient]
SUBJECT = subject
TEXT = body
# Prepare actual message
message = """From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
server = smtplib.SMTP_SSL("mail.openedoo.org", 465)
server.ehlo()
#server.starttls()
server.login(mail_user, mail_password)
server.sendmail(FROM, TO, message)
server.close()
return 'successfully sent the mail'
except Exception as e:
return "failed to send mail"
python类SMTP_SSL的实例源码
def call(self, when, cm, collect_point_results, backup_point_results):
self.set_extra_variables(cm, collect_point_results, backup_point_results)
msg = MIMEText(self.format_value(self.content))
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = self.format_value(self.subject)
msg['From'] = self.format_value(self.sender)
msg['To'] = self.format_value(self.recipient)
# Send the message via our own SMTP server.
if self.encryption == "tls":
smtp = smtplib.SMTP_SSL(host=self.hostname, port=self.port, keyfile=self.keyfile, certfile=self.certfile)
else:
smtp = smtplib.SMTP(host=self.hostname, port=self.port)
if self.encryption == 'starttls':
smtp.starttls(keyfile=self.keyfile, certfile=self.certfile)
if self.username and self.password:
smtp.login(self.username, self.password)
smtp.send_message(msg)
smtp.quit()
def init_server(self):
self.logger.info("Initializing SMTP/IMAP servers.")
# PySMS at minimum uses smtp server
try:
if self.ssl:
self.smtp = smtplib.SMTP_SSL(self.smtp_server, self.smtp_port)
else:
self.smtp = smtplib.SMTP(self.smtp_server, self.smtp_port)
self.smtp.starttls()
self.smtp.login(self.address, self.password)
except smtplib.SMTPException:
raise PySMSException("Unable to start smtp server, please check credentials.")
# If responding functionality is enabled
if self.imap_server:
try:
if self.ssl:
self.imap = imaplib.IMAP4_SSL(self.imap_server)
else:
self.imap = imaplib.IMAP4(self.imap_server)
r, data = self.imap.login(self.address, self.password)
if r == "OK":
r, data = self.imap.select(self.imap_mailbox)
if r != "OK":
raise PySMSException("Unable to select mailbox: {0}".format(self.imap_mailbox))
else:
raise PySMSException("Unable to login to IMAP server with given credentials.")
except imaplib.IMAP4.error:
raise PySMSException("Unable to start IMAP server, please check address and SSL/TLS settings.")
def _test_mail(self):
try:
if self.mail_port == 465:
smtp = SMTP_SSL(self.mail_host, port=self.mail_port, timeout=2)
else:
smtp = SMTP(self.mail_host, port=self.mail_port, timeout=2)
smtp.login(self.mail_addr, self.mail_pass)
smtp.sendmail(self.mail_addr, (self.mail_addr, ),
'''From:%s\r\nTo:%s\r\nSubject:GeekCloud Mail Test!\r\n\r\n Mail test passed!\r\n''' %
(self.mail_addr, self.mail_addr))
smtp.quit()
return True
except Exception, e:
color_print(e, 'red')
skip = raw_input('????(y/n) [n]? : ')
if skip == 'y':
return True
return False
def get_smtp_server():
"""
Instanciate, configure and return a SMTP or SMTP_SSL instance from
smtplib.
:return: A SMTP instance. The quit() method must be call when all
the calls to sendmail() have been made.
"""
uri = parse_uri(config.get('email', 'uri'))
if uri.scheme.startswith('smtps'):
smtp_server = smtplib.SMTP_SSL(uri.hostname, uri.port)
else:
smtp_server = smtplib.SMTP(uri.hostname, uri.port)
if 'tls' in uri.scheme:
smtp_server.starttls()
if uri.username and uri.password:
smtp_server.login(
urllib.unquote_plus(uri.username),
urllib.unquote_plus(uri.password))
return smtp_server
def send_invite(user):
if _cfg("smtp-host") == "":
return
smtp = smtplib.SMTP_SSL(_cfg("smtp-host"), _cfgi("smtp-port"))
smtp.ehlo()
smtp.login(_cfg("smtp-user"), _cfg("smtp-password"))
with open("emails/invite") as f:
message = MIMEText(html.parser.HTMLParser().unescape(\
pystache.render(f.read(), {
'user': user,
"domain": _cfg("domain"),
"protocol": _cfg("protocol")
})))
message['Subject'] = "Your wank.party account is approved"
message['From'] = _cfg("smtp-user")
message['To'] = user.email
smtp.sendmail(_cfg("smtp-user"), [ user.email ], message.as_string())
smtp.quit()
def send_reset(user):
if _cfg("smtp-host") == "":
return
smtp = smtplib.SMTP_SSL(_cfg("smtp-host"), _cfgi("smtp-port"))
smtp.ehlo()
smtp.login(_cfg("smtp-user"), _cfg("smtp-password"))
with open("emails/reset") as f:
message = MIMEText(html.parser.HTMLParser().unescape(\
pystache.render(f.read(), {
'user': user,
"domain": _cfg("domain"),
"protocol": _cfg("protocol"),
'confirmation': user.passwordReset
})))
message['Subject'] = "Reset your wank.party password"
message['From'] = _cfg("smtp-user")
message['To'] = user.email
smtp.sendmail(_cfg("smtp-user"), [ user.email ], message.as_string())
smtp.quit()
def send_txt(self, filename):
# ????????????????????????????????????
self.smtp = smtplib.SMTP_SSL(port=465)
self.smtp.connect(self.server)
self.smtp.login(self.username, self.password)
#self.msg = MIMEMultipart()
self.msg = MIMEText("content", 'plain', 'utf-8')
self.msg['to'] = self.to_mail
self.msg['from'] = self.from_mail
self.msg['Subject'] = "459"
self.filename = filename + ".txt"
self.msg['Date'] = Utils.formatdate(localtime=1)
content = open(self.filename.decode('utf-8'), 'rb').read()
# print content
#self.att = MIMEText(content, 'base64', 'utf-8')
#self.att['Content-Type'] = 'application/octet-stream'
# self.att["Content-Disposition"] = "attachment;filename=\"%s\"" %(self.filename.encode('gb2312'))
#self.att["Content-Disposition"] = "attachment;filename=\"%s\"" % Header(self.filename, 'gb2312')
# print self.att["Content-Disposition"]
#self.msg.attach(self.att)
#self.smtp.sendmail(self.msg['from'], self.msg['to'], self.msg.as_string())
self.smtp.sendmail(self.msg['from'], self.msg['to'], self.msg.as_string())
self.smtp.quit()
def _send(self, strTitle, strContent, listToAddr):
msg = MIMEText(strContent, 'plain', 'utf-8')
# ?????:
msg['From'] = self._format_addr(u'DB?? <%s>' % self.MAIL_FROM_ADDR)
#msg['To'] = self._format_addr(listToAddr)
msg['To'] = ','.join(listToAddr)
msg['Subject'] = Header(strTitle, "utf-8").encode()
server = smtplib.SMTP_SSL(self.MAIL_SMTP_SERVER, self.MAIL_SMTP_PORT)
#server.set_debuglevel(1)
#????????????????SMTP server
if self.MAIL_FROM_PASSWORD != '':
server.login(self.MAIL_FROM_ADDR, self.MAIL_FROM_PASSWORD)
sendResult = server.sendmail(self.MAIL_FROM_ADDR, listToAddr, msg.as_string())
server.quit()
#??????????????????????????????????????wizard???
def _test_mail(self):
try:
if self.mail_port == 465:
smtp = SMTP_SSL(self.mail_host, port=self.mail_port, timeout=2)
else:
smtp = SMTP(self.mail_host, port=self.mail_port, timeout=2)
smtp.login(self.mail_addr, self.mail_pass)
smtp.sendmail(self.mail_addr, (self.mail_addr, ),
'''From:%s\r\nTo:%s\r\nSubject:GeekCloud Mail Test!\r\n\r\n Mail test passed!\r\n''' %
(self.mail_addr, self.mail_addr))
smtp.quit()
return True
except Exception, e:
color_print(e, 'red')
skip = raw_input('????(y/n) [n]? : ')
if skip == 'y':
return True
return False
def send_MIME_email(e_from, e_to, mime_msg, dryrun=False):
log = LoggingMixin().log
SMTP_HOST = configuration.get('smtp', 'SMTP_HOST')
SMTP_PORT = configuration.getint('smtp', 'SMTP_PORT')
SMTP_STARTTLS = configuration.getboolean('smtp', 'SMTP_STARTTLS')
SMTP_SSL = configuration.getboolean('smtp', 'SMTP_SSL')
SMTP_USER = None
SMTP_PASSWORD = None
try:
SMTP_USER = configuration.get('smtp', 'SMTP_USER')
SMTP_PASSWORD = configuration.get('smtp', 'SMTP_PASSWORD')
except AirflowConfigException:
log.debug("No user/password found for SMTP, so logging in with no authentication.")
if not dryrun:
s = smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT) if SMTP_SSL else smtplib.SMTP(SMTP_HOST, SMTP_PORT)
if SMTP_STARTTLS:
s.starttls()
if SMTP_USER and SMTP_PASSWORD:
s.login(SMTP_USER, SMTP_PASSWORD)
log.info("Sent an alert email to %s", e_to)
s.sendmail(e_from, e_to, mime_msg.as_string())
s.quit()
def ba_smtp_sendEmail(email_title, email_content, email_type, email_sender, email_receiver, email_host, email_user, email_pwd):
# ??, ??, ??
message = MIMEText(email_content, email_type, 'utf-8')
message['From'] = '{}'.format(email_sender)
message['To'] = ','.join(email_receiver)
message['Subject'] = email_title
try:
# ??SSL??, ?????465
smtpObj = smtplib.SMTP_SSL(email_host, 465)
# ????
smtpObj.login(email_user, email_pwd)
# ??
smtpObj.sendmail(email_sender, email_receiver, message.as_string())
print('??????!')
except smtplib.SMTPException as e:
print("Error: ??????")
print(e)
def send_txt(self, name, price, percent, status):
if 'up' == status:
content = '%s > %.2f , %.2f' % (name, price, percent)
if 'down' == status:
content = '%s < %.2f , %.2f' % (name, price, percent)
content = content + '%'
print content
subject = '%s' % name
self.msg = MIMEText(content, 'plain', 'utf-8')
self.msg['to'] = self.to_mail
self.msg['from'] = self.from_mail
self.msg['Subject'] = subject
self.msg['Date'] = Utils.formatdate(localtime=1)
try:
self.smtp = smtplib.SMTP_SSL(port=465)
self.smtp.connect(self.server)
self.smtp.login(self.username, self.password)
self.smtp.sendmail(self.msg['from'], self.msg['to'], self.msg.as_string())
self.smtp.quit()
print "sent"
except smtplib.SMTPException, e:
print e
return 0
def _test_mail(self):
try:
if self.mail_port == 465:
smtp = SMTP_SSL(self.mail_host, port=self.mail_port, timeout=2)
else:
smtp = SMTP(self.mail_host, port=self.mail_port, timeout=2)
smtp.login(self.mail_addr, self.mail_pass)
smtp.sendmail(self.mail_addr, (self.mail_addr, ),
'''From:%s\r\nTo:%s\r\nSubject:Jumpserver Mail Test!\r\n\r\n Mail test passed!\r\n''' %
(self.mail_addr, self.mail_addr))
smtp.quit()
return True
except Exception, e:
color_print(e, 'red')
skip = raw_input('????(y/n) [n]? : ')
if skip == 'y':
return True
return False
def send_email(subject, content, excel_path, receivers_array):
contype = 'application/octet-stream'
maintype, subtype = contype.split('/', 1)
server = smtplib.SMTP_SSL(host=configUtil.get("email.host"),port=configUtil.get("email.port"))
server.login(configUtil.get("email.username"), configUtil.get("email.password"))
main_msg = MIMEMultipart()
text_msg = MIMEText(content, 'plain', "utf-8")
# email text
main_msg.attach(text_msg)
# email attach
print "excel path:" + str(excel_path)
data = open(excel_path, 'rb')
attach = MIMEText(data.read(), 'base64', 'gb2312')
basename = os.path.basename(excel_path)
attach["Content-Type"] = 'application/octet-stream'
attach.add_header('Content-Disposition', 'attachment', filename=basename.encode("gb2312"))
main_msg.attach(attach)
main_msg["Accept-Language"] = "zh-CN"
main_msg["Accept-Charset"] = "utf-8"
main_msg['From'] = configUtil.get("email.username")
main_msg['To'] = ",".join(receivers_array)
main_msg['Subject'] = subject
full_text = main_msg.as_string()
server.sendmail(configUtil.get("email.username"), receivers_array, full_text)
server.quit()
def send_email(sub,cont):
# send email
global my_email,my_password
sender = my_email # ???
receiver = [my_email] # ???
subject = sub # ????
smtpserver = 'smtp.qq.com' # ?????
username = my_email # ???
password = my_password # ???
msg = MIMEText(cont, 'html', 'utf8') # ????
msg['Subject'] = Header(subject, 'utf8') # ????
msg['From'] = sender # ?????
msg['To'] = ','.join(receiver) # ?????
smtp = smtplib.SMTP_SSL(smtpserver,465)
#smtp.connect(smtpserver)
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
def status(request):
logger.info("Status request received")
settings = request.registry.settings
host = settings["edwiges.provider_host"]
port = settings["edwiges.provider_port"]
with SMTP_SSL(host, port) as smtp:
try:
_, status = smtp.noop()
errors = []
except Exception as e:
status = "failed"
errors = [str(e)]
return {"status": status, "errors": errors}
def send_email(recipient, subject, body):
import smtplib
gmail_user = get_ini_setting('notification_emails', 'gmail_user')
if gmail_user is not None:
gmail_password = get_ini_setting('notification_emails', 'gmail_password')
if gmail_password is None:
return
FROM = gmail_user
TO = recipient if type(recipient) is list else [recipient]
SUBJECT = subject
TEXT = body
# Prepare actual message
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
server_ssl = smtplib.SMTP_SSL("smtp.gmail.com", 465)
server_ssl.ehlo() # optional, called by login()
server_ssl.login(gmail_user, gmail_password)
server_ssl.sendmail(FROM, TO, message)
server_ssl.close()
def sendemali(filepath): #??email
from_addr,password,mail_to,mail_body=load_emil_setting()
msg = MIMEMultipart()
msg['Subject'] = '?????????'
msg['From'] ='???????'
msg['To'] = mail_to
msg['Date'] = time.strftime('%a, %d %b %Y %H:%M:%S %z')
att = MIMEText(open(r'%s'%filepath, 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="pyresult.html"'
txt = MIMEText("???????????????",'plain','gb2312')
msg.attach(txt)
msg.attach(att)
smtp = smtplib.SMTP()
server = smtplib.SMTP_SSL("smtp.qq.com",465)
server.login(from_addr, password)
server.sendmail(from_addr, mail_to, msg.as_string())
server.quit()
def send_mail(toaddrs, subject, text):
if toaddrs is None or len(toaddrs) == 0:
return
fromaddr = envget('mailsender.fromaddr')
msg = MIMEText(text)
msg['Subject'] = subject
msg['From'] = fromaddr
msg['To'] = toaddrs
# Credentials (if needed)
username = envget('mailsender.username')
password = envget('mailsender.password')
# The actual mail send
server = smtplib.SMTP_SSL(
envget('mailsender.smtp_host'), envget('mailsender.smtp_ssl_port'))
server.login(username, password)
server.sendmail(fromaddr, toaddrs, msg.as_string())
server.quit()
def send_email(msg, email_login_address, email_login_password, email_smtp_server, email_smtp_port,
email_to_addresses, email_smtp_starttls):
subject = 'Lending bot'
email_text = "\r\n".join(["From: {0}".format(email_login_address),
"To: {0}".format(", ".join(email_to_addresses)),
"Subject: {0}".format(subject),
"",
"{0}".format(msg)
])
try:
if email_smtp_starttls:
server = smtplib.SMTP(email_smtp_server, email_smtp_port)
server.ehlo()
server.starttls()
else:
server = smtplib.SMTP_SSL(email_smtp_server, email_smtp_port)
server.ehlo()
server.login(email_login_address, email_login_password)
server.sendmail(email_login_address, email_to_addresses, email_text)
server.close()
except Exception as e:
print("Could not send email, got error {0}".format(e))
raise NotificationException(e)
def send_mail(sub,content, href):
me="????"+"<"+mail_user+"@"+mail_postfix+">"
content += '<br/><a href="%s%s">??<%s></a>'%(settings['ROOT_URL'],href, sub)
msg = MIMEText(content,_subtype='html',_charset='utf-8')
msg['Subject'] = sub
msg['From'] = me
msg['To'] = ";".join(mailto_list)
try:
server = smtplib.SMTP_SSL(mail_host, 465)
server.set_debuglevel(1)
server.login(mail_user,mail_pass)
server.sendmail(me, mailto_list, msg.as_string())
server.close()
return True
except Exception, e:
print str(e)
return False
def notify(self, model):
try:
fromAddr = self._from
toAddr = self._to.split()
subj = self._subject.format(**model)
body = self._body.format(**model)
message = "From: {frm}\nTo: {to}\nSubject: {subject}\n\n{body}".format(frm=self._from, to=self._to, subject=subj, body=body)
if self._ssl:
server = smtplib.SMTP_SSL(self._host, self._port)
else:
server = smtplib.SMTP(self._host, self._port)
server.ehlo()
if self._username:
if (self._tls):
server.starttls()
server.login(self._username, self._password)
server.sendmail(fromAddr, toAddr, message)
server.close()
except Exception, e:
logging.error("There was an error sending an email %s" % e)
def send_MIME_email(e_from, e_to, mime_msg, dryrun=False):
SMTP_HOST = configuration.get('smtp', 'SMTP_HOST')
SMTP_PORT = configuration.getint('smtp', 'SMTP_PORT')
SMTP_USER = configuration.get('smtp', 'SMTP_USER')
SMTP_PASSWORD = configuration.get('smtp', 'SMTP_PASSWORD')
SMTP_STARTTLS = configuration.getboolean('smtp', 'SMTP_STARTTLS')
SMTP_SSL = configuration.getboolean('smtp', 'SMTP_SSL')
if not dryrun:
s = smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT) if SMTP_SSL else smtplib.SMTP(SMTP_HOST, SMTP_PORT)
if SMTP_STARTTLS:
s.starttls()
if SMTP_USER and SMTP_PASSWORD:
s.login(SMTP_USER, SMTP_PASSWORD)
logging.info("Sent an alert email to " + str(e_to))
s.sendmail(e_from, e_to, mime_msg.as_string())
s.quit()
def _test_mail(self):
try:
if self.mail_port == 465:
smtp = SMTP_SSL(self.mail_host, port=self.mail_port, timeout=2)
else:
smtp = SMTP(self.mail_host, port=self.mail_port, timeout=2)
smtp.login(self.mail_addr, self.mail_pass)
smtp.sendmail(self.mail_addr, (self.mail_addr, ),
'''From:%s\r\nTo:%s\r\nSubject:Jumpserver Mail Test!\r\n\r\n Mail test passed!\r\n''' %
(self.mail_addr, self.mail_addr))
smtp.quit()
return True
except Exception, e:
color_print(e, 'red')
skip = raw_input('????(y/n) [n]? : ')
if skip == 'y':
return True
return False
def mail(self):
"""
??????????????????
"""
getCodeUrl = 'https://api.weibo.com/oauth2/authorize?client_id={app_key}&redirect_uri={redirect_uri}'.format(
app_key=self.app_key, redirect_uri=self.redirect_uri)
line1 = "??????{error}".format(error=self.error)
line2 = "????code????????~"
line3 = "?????{url}".format(url=getCodeUrl)
msg = MIMEText(('<font color=#000000><br>{line1}<br>{line2}<br>{line3}</font>'
.format(line1=line1, line2=line2, line3=line3)), 'html', 'utf-8')
msg["Subject"] = "???????????"
msg["From"] = self.account
msg["To"] = self.recipient
try:
server = smtplib.SMTP_SSL("smtp.qq.com", 465)
server.login(self.account, self.password)
server.sendmail(self.account, self.recipient, msg.as_string())
server.quit()
except:
print("Because the mail sending error can not be reminded to the developer, to stop the program running")
sys.exit(0)
def mail(self):
"""
???????????????????????
"""
'''??????'''
msg = MIMEText('???????????????????', 'html', 'utf-8')
msg["Subject"] = "??????????"
msg["From"] = self.my_sender
msg["To"] = self.my_user
try:
server = smtplib.SMTP_SSL("smtp.qq.com", 465)
server.login(self.my_sender, self.my_pass)
server.sendmail(self.my_sender, self.my_user, msg.as_string())
server.quit()
print('??????')
except Exception:
print('??????')
def send_email(email):
from_address = config.EMAIL_ADDRESS_JARVIS
to_addresses = email.to
cc_addresses = [config.EMAIL_ADDRESS_CC]
# compose message
msg = MIMEMultipart()
msg['From'] = from_address
msg['To'] = ','.join(to_addresses)
msg['Cc'] = ','.join(cc_addresses)
msg['Subject'] = email.subject
message_content = '\n'.join([email.message, get_signature()])
mime_text = MIMEText(message_content, 'plain')
msg.attach(mime_text)
with smtplib.SMTP_SSL(config.EMAIL_SMTP_HOST, config.EMAIL_SMTP_PORT) as s:
# todo works for me but not for everyone
s.ehlo()
s.login(config.EMAIL_IMAP_USER, config.EMAIL_IMAP_PASSWORD)
s.send_message(msg)
def send(self):
# try:
print 'before format_text_html'
self._format_text_html()
print 'message_text {0}'.format(self.message_text)
logger.info('message_text {0}'.format(self.message_text))
self._format_head()
smtpObj = smtplib.SMTP_SSL(self.mail_host)
logger.info('Trying Connect')
print 'Trying Connect'
# logger.info('Connnect Successfully')
smtpObj.login(self.mail_user,self.mail_pass)
logger.info('Login Successfully')
print 'Login Successfully'
smtpObj.sendmail(self.message['From'], self.receivers_email, self.message.as_string())
print 'send email successful'
# except Exception, e:
# print 'Error during send email'
# print str(e)
def _send_mail(self, subject, body):
"""
Send a simple text e-mail. Settings are used to get the recipient.
:param str subject: Subject of the email
:param str body: Body content of the email
"""
try:
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = settings.SCORING_EMAIL['reporting']['from']
msg['To'] = settings.SCORING_EMAIL['reporting']['to']
smtp = smtplib.SMTP_SSL(settings.SCORING_EMAIL['host'])
smtp.sendmail(msg['From'], msg['To'], msg.as_string())
smtp.quit()
except Exception as ex:
LOGGER.error('Something went wrong when sending the email: %s', ex)