def _configure_smtp(self) -> None: if self.smtp_using_ssl: self.smtp_using_tls = False elif self.smtp_using_tls: self.smtp_using_ssl = False if not self.is_smtp or self.is_smtp == '': raise InsufficientError('is_smtp') if not self.username or self.username == '': raise InsufficientError('username') if not self.password or self.password == '': raise InsufficientError('password') if not self.smtp_server or self.smtp_server == '': raise InsufficientError('smtp_server') if not self.smtp_port or self.smtp_port == '': raise InsufficientError('smtp_port') if not self.smtp_using_ssl and not self.smtp_using_tls: raise InsufficientError('smtp_using_ssl, smtp_using_tls') if self.smtp_using_tls: # for smtp using start_tls self.smtp:SMTP = SMTP(self.smtp_server, self.smtp_port) self.smtp.ehlo() self.smtp.starttls() elif self.smtp_using_ssl: # for smtp using start_ssl self.smtp:SMTP_SSL = SMTP_SSL(self.smtp_server, self.smtp_port) try: self.smtp.login(self.username, self.password) except Exception as e: raise SMTPLoginError([self.username, self.password], e)
def send_mail(subject, message, from_email, recipient_email): msg = MIMEMultipart() msg['From'] = from_email msg['To'] = recipient_email msg['Subject'] = subject msg.attach(MIMEText(message, 'plain')) try: with SMTP_SSL(host=SMTP_HOST, port=SMTP_PORT) as smtp: smtp.set_debuglevel(False) smtp.ehlo() smtp.login(MAIL_USER, MAIL_PASS) smtp.sendmail(MAIL_USER, recipient_email, msg.as_string()) smtp.quit() except SMTPException as e: print(e)
def check_smtp_ssl(hostname, port, username="", password=""): ''' Test the SMTP Connection if can connect and auth using SSL :param hostname: The smtp hostname :param port: The smtp port :param username: The smtp username (Optional) :param password: The smtp passworf (Optional) :return: A dictionary with the results ''' smtp = SMTP_SSL() connection_report = test_connection(smtp, hostname, port, username, password) smtp_quit(smtp) return connection_report
def send_mail(cls, mail_from='', mail_to=None, host='', username='', password='', subject='', content='', content_type='plain', encoding='utf-8'): # 这里使用SMTP_SSL就是默认使用465端口 smtp = SMTP_SSL(host) smtp.set_debuglevel(1) smtp.ehlo(host) smtp.login(username, password) msg = MIMEText(content, content_type, encoding) msg["Subject"] = Header(subject, encoding) msg["From"] = mail_from msg["To"] = mail_to smtp.sendmail(mail_from, mail_to, msg.as_string()) smtp.quit()
def send_mail(smtp_info, target_mail, subject, contents, attachment=False): msg = MIMEMultipart("alternative") if attachment: msg = MIMEMultipart('mixed') msg['From'] = smtp_info.user_mail msg['to'] = target_mail msg['Subject'] = subject text = MIMEText(contents) msg.attach(text) smtp = SMTP_SSL(smtp_info.server, smtp_info.port) smtp.login(smtp_info.user, smtp_info.password) smtp.sendmail(smtp_info.user_mail, target_mail, msg.as_string()) smtp.close()
def send_email(from_address, to_addresses, subject, body_text, body_html): """Sends an email with the inputted details using the WebFaction SMTP server.""" # Create the message # message = MIMEText(body_text) message = MIMEText(body_html, "html") message["Subject"] = subject # Connect to the server, send the email, and disconnect from the server server = SMTP_SSL("smtp.webfaction.com", 465) server.login("inkle", "AmiTabh-2012") if (DEBUG): to_addresses = ["*****@*****.**"] server.sendmail(from_address, to_addresses, message.as_string()) server.quit()
def send_mail(text, to): login, _, password = netrc().authenticators('smtp.gmail.com') if not login or not password: raise Exception('No login/password found in netrc') email = '''\ From: {} To: {} Subject: Classes at The Gym - Ealing {} '''.format(login, ', '.join(to), text) print('Sending e-mail to: {}'.format(', '.join(to))) with SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.ehlo() smtp.login(login, password) smtp.sendmail(login, to, email)
def send_email_update(old_ip, new_ip): hostname = str(sh.hostname('-s')).strip() date_time = get_date() HOST = "{}:{}".format(sender_server, int(sender_port)) TO = "To: {}".format(receiver_address) FROM = "From: {}".format(sender_address) SUBJECT = "Subject: {}'s WAN IP has changed!".format(hostname) msg = "{}\n\n{}'s WAN IP has changed from {} to {}".format( date_time, hostname, old_ip, new_ip) BODY = "{}\n{}\n{}\n\n{}".format(TO, FROM, SUBJECT, msg) username = "******".format(sender_username) password = "******".format(sender_password) server = SMTP_SSL(HOST) server.login(username, password) server.sendmail(FROM, TO, BODY) server.quit()
def mail_sender(tmp, receivers, mail_title): #邮件的正文内容 mail_content = tmp #邮件标题 mail_title = '矿机状态消息' #ssl登录 smtp = SMTP_SSL(host_server) #set_debuglevel()是用来调试的。参数值为1表示开启调试模式,参数值为0关闭调试模式 smtp.set_debuglevel(0) smtp.ehlo(host_server) smtp.login(sender_qq, pwd) msg = MIMEText(mail_content, "plain", 'utf-8') msg["Subject"] = Header(mail_title, 'utf-8') msg["From"] = sender_qq_mail msg["To"] = Header("嘤嘤怪的vps", 'utf-8') ## 接收者的别名 smtp.sendmail(sender_qq_mail, receivers, msg.as_string()) smtp.quit()
def send_mail( smtp_server, port, sender_email, sender_password, receiver_email, # pylint: disable=too-many-arguments message): """Sending credentials to user. """ context = ssl.create_default_context() with SMTP_SSL(smtp_server, port, context=context) as server: server.login(sender_email, sender_password) msg = EmailMessage() msg['Subject'] = 'Your hubot-huntflow credentials' msg['From'] = sender_email msg['To'] = receiver_email msg.set_content(message) server.sendmail(sender_email, receiver_email, msg.as_string())
def send_mail(): smtp = SMTP_SSL(mailInfo["hostname"]) smtp.set_debuglevel(1) smtp.ehlo(mailInfo["hostname"]) smtp.login(mailInfo["username"], mailInfo["password"]) msg = MIMEText(mailInfo["mailtext"], mailInfo["mailtype"], mailInfo["mailencoding"]) msg["Subject"] = Header(mailInfo["mailsubject"], mailInfo["mailencoding"]) msg["from"] = mailInfo["from"] msg["to"] = mailInfo["to"] msg["Accept-Language"] = "zh-CN" msg["Accept-Charset"] = "ISO-8859-1,utf-8" smtp.sendmail(mailInfo["from"], mailInfo["to"], msg.as_string()) smtp.quit()
def sendmail(sendto="*****@*****.**", mail_text='已完成'): mail_info["to"] = sendto mail_info["mail_text"] = mail_text smtp = SMTP_SSL(mail_info["hostname"]) smtp.set_debuglevel(1) smtp.ehlo(mail_info["hostname"]) smtp.login(mail_info["username"], mail_info["password"]) msg = MIMEText(mail_info["mail_text"] + str(random.random()), "plain", mail_info["mail_encoding"]) msg["Subject"] = Header(mail_info["mail_subject"], mail_info["mail_encoding"]) msg["from"] = mail_info["from"] msg["to"] = mail_info["to"] smtp.sendmail(mail_info["from"], mail_info["to"], msg.as_string()) smtp.quit()
def sendEmail(mail_content='测试', mail_title='辣鸡,又出错了...'): with open(sendEmailConfig, 'r') as f: config = json.load(f) # ssl登录 smtp = SMTP_SSL(config["server"]) # set_debuglevel()是用来调试的。参数值为1表示开启调试模式,参数值为0关闭调试模式 smtp.set_debuglevel(0) smtp.ehlo(config["server"]) smtp.login(config["sender"], config["pwd"]) msg = MIMEText(str(mail_content), "plain", 'utf-8') msg["Subject"] = Header(mail_title, 'utf-8') msg["From"] = config["senderName"] + "<%s>" % config["sender"] for receiver in config["receiver"]: msg["To"] = receiver smtp.sendmail(config["sender"], receiver, msg.as_string()) smtp.quit()
def connect(self): if self.security == 'none' or self.security == '': smtp = SMTP(self.host, self.port) else: ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) ssl_context.load_cert_chain(config.Smtp.tls_cert_file, config.Smtp.tls_key_file) if self.security == 'starttls': smtp = SMTP(self.host, self.port) smtp.starttls(ssl_context) elif self.security == 'tls': smtp = SMTP_SSL(self.host, self.port, ssl_context=ssl_context) if self.username != None: smtp.login(self.username, self.password) return smtp
def send_email(self): msgAlternative = MIMEMultipart() msgAlternative['From'] = self.USER msgAlternative['Subject'] = Header(self.Subject, 'utf-8') msgAlternative['To'] = Header(",".join(x for x in self.TO_LIST)) if self.CC_LIST: msgAlternative['Cc'] = Header(",".join(x for x in self.CC_LIST)) # # 设定纯文本信息 msgHtml = MIMEText(self.__get_str(), 'html', 'utf-8') msgAlternative.attach(msgHtml) # 设定内置图片信息 if self.images: for cid in self.images.keys(): i = self.__get_image(cid, self.images[cid]) msgAlternative.attach(i) # 设定附件 if self.attr: for file in self.attr: i = self.__get_file(file) msgAlternative.attach(i) if self.PORT == 25: try: smtp_obj = SMTP(self.SMTP, self.PORT) smtp_obj.connect(self.SMTP, self.PORT) smtp_obj.login(self.USER, self.PW) smtp_obj.sendmail(self.USER, self.TO_LIST + self.CC_LIST, msgAlternative.as_string()) smtp_obj.close() return True, "邮件发送成功" except SMTPException as e: return False, "邮件发送失败: {}".format(e) elif self.PORT == 465: try: smtp_obj = SMTP_SSL(self.SMTP, self.PORT) smtp_obj.ehlo() smtp_obj.login(self.USER, self.PW) smtp_obj.sendmail(self.USER, self.TO_LIST + self.CC_LIST, msgAlternative.as_string()) smtp_obj.close() return True, "邮件发送成功" except SMTPException as e: return False, "邮件发送失败: {}".format(e)
def authorize_smtp( self, account: str = None, password: str = None, smtp_server: str = None, smtp_port: int = None, ) -> None: """Authorize to SMTP server. Can be called without giving any parameters if library has been initialized with necessary information and/or keyword ``set_credentials`` has been used. :param account: SMTP account name, defaults to None :param password: SMTP account password, defaults to None :param smtp_server: SMTP server address, defaults to None :param smtp_port: SMTP server port, defaults to None (587 for SMTP) """ if account is None and password is None: account = self.account password = self.password if smtp_server is None: smtp_server = self.smtp_server if smtp_port is None: smtp_port = self.smtp_port else: smtp_port = int(smtp_port) if smtp_server and account and password: try: self.smtp_conn = SMTP(smtp_server, smtp_port) self.send_smtp_hello() try: self.smtp_conn.starttls() except SMTPNotSupportedError: self.logger.warning("TLS not supported by the server") except SMTPConnectError: context = ssl.create_default_context() self.smtp_conn = SMTP_SSL(smtp_server, smtp_port, context=context) self.smtp_conn.login(account, password) else: self.logger.warning( "Server address, account and password are needed for " "authentication with SMTP" ) if self.smtp_conn is None: self.logger.warning("Not able to establish SMTP connection")
def send_email(email, subject, content): fromaddr = '*****@*****.**' password = '******' # Configuration message msg = MIMEText(content, 'html') msg['From'] = fromaddr msg['To'] = email msg['Subject'] = subject # Send e-mail smtp = SMTP_SSL('smtp.mail.ru:465') smtp.ehlo() smtp.login(fromaddr, password) smtp.sendmail(fromaddr, email, msg.as_string()) smtp.quit() return True
def maillog(subject, msg): if (not smtp_host or not smtp_port or not smtp_user or not smtp_pass or not smtp_from or not recipients): return smtp = SMTP_SSL('%s:%s' % (smtp_host, smtp_port), context=None) smtp.login(smtp_user, smtp_pass) message = MIMEMultipart("alternative") message['Subject'] = subject message['From'] = smtp_from message['To'] = recipients part1 = MIMEText(msg, "plain", "utf-8") message.attach(part1) smtp.sendmail(smtp_from, recipients, message.as_string())
def send_mail(target_mail, subject, contents, attachment=False): msg = MIMEMultipart("alternative") if attachment: msg = MIMEMultipart('mixed') msg['From'] = SMTP_USER_MAIL msg['to'] = target_mail msg['Subject'] = subject text = MIMEText(contents) msg.attach(text) smtp = SMTP_SSL(SMTP_SERVER, SMTP_PORT) smtp.login(SMTP_USER, SMTP_PASSWORD) smtp.sendmail(SMTP_USER_MAIL, target_mail, msg.as_string()) smtp.close()
def __init__(self, mailname, pwd, ssl=True): self.mailname = mailname server = parse_mail(mailname).get('smtp', '') self.server = SMTP(server.get('host'), server.get('port')) if ssl == True: # TODO SSL self.server = SMTP_SSL(server.get('host'), server.get('ssl_port'), context=context) else: self.server = SMTP(server.get('host'), server.get('port')) self.server.login(mailname, pwd)
def send(): # 这里使用SMTP_SSL就是默认使用465端口 smtp = SMTP_SSL(mail_info["hostname"]) smtp.set_debuglevel(1) smtp.ehlo(mail_info["hostname"]) smtp.login(mail_info["username"], mail_info["password"]) msg = MIMEText(mail_info["mail_text"], "plain", mail_info["mail_encoding"]) msg["Subject"] = Header(mail_info["mail_subject"], mail_info["mail_encoding"]) msg["from"] = mail_info["from"] msg["to"] = mail_info["to"] smtp.sendmail(mail_info["from"], mail_info["to"], msg.as_string()) smtp.quit()
def send_message(self, prefix, to_addr, head, message): try: msg = MIMEText(message, 'plain', 'utf-8') msg['From'] = self.format_addr(u'%s <%s>' % (prefix, self.from_addr)) msg['To'] = self.format_addr(u'<%s>' % to_addr) msg['Subject'] = Header(head, 'utf-8').encode() server = SMTP_SSL(self.smtp_server, self.smtp_port) #server.set_debuglevel(1) server.login(self.from_addr, self.password) server.sendmail(self.from_addr, [to_addr], msg.as_string()) server.quit() print('send email successfully') except: print('send email failed') traceback.print_exc()
def send(self, text): # 这里使用SMTP_SSL就是默认使用465端口,如果发送失败,可以使用587 smtp = SMTP_SSL(self.mail_info['hostname']) smtp.set_debuglevel(0) ''' SMTP 'ehlo' command. Hostname to send for this command defaults to the FQDN of the local host. ''' smtp.ehlo(self.mail_info['hostname']) smtp.login(self.mail_info['username'], self.mail_info['password']) #普通的HTML邮件 # msg = MIMEText(text, 'html', self.mail_info['mail_encoding']) #带附件的发送 msg = MIMEMultipart() msg.attach(MIMEText(text, 'html', self.mail_info['mail_encoding'])) msg['Subject'] = Header(self.mail_info['mail_subject'], self.mail_info['mail_encoding']) msg['from'] = self.mail_info['from'] logger.debug(self.mail_info) logger.debug(text) msg['to'] = ','.join(self.mail_info['to']) msg['cc'] = ','.join(self.mail_info['cc']) receive = self.mail_info['to'] receive += self.mail_info['cc'] # 添加附件 for i in range(len(self.mail_info['filepaths'])): att1 = MIMEText( open(self.mail_info['filepaths'][i], 'rb').read(), 'base64', 'utf-8') att1['Content-Type'] = 'application/octet-stream' att1[ 'Content-Disposition'] = 'attachment; filename= "' + self.mail_info[ 'filenames'][i] + '"' msg.attach(att1) try: smtp.sendmail(self.mail_info['from'], receive, msg.as_string()) smtp.quit() logger.info('邮件发送成功') except Exception as e: logger.error('邮件发送失败:') logger.exception(e)
def send_mail(self, title, content): ret = True try: msg = MIMEText(content, 'html', self.charset) msg['From'] = formataddr(['工具人', self.sender]) msg['To'] = formataddr(['aim', self.aimMail]) msg['Subject'] = title server = SMTP_SSL('smtp.qq.com', 465) server.login(self.sender, self.MailPass) server.sendmail(self.sender, [ self.aimMail, ], msg.as_string()) server.quit() except Exception as e: print(e) ret = False return ret
def send_email(text_news, text_exam): smtp_server = 'smtp.qq.com' smtp_port = '465' from_addr = '你的发送邮箱地址(默认为QQmail)' password = '******' to_addr = '你的接收邮箱地址' message = MIMEText('%s' % text_news + text_exam, 'html', 'utf-8') message['From'] = Header("Auto_Push", 'utf-8') message['To'] = Header("me", 'utf-8') message['Subject'] = Header("教务处信息更新", 'utf-8').encode() server_s = SMTP_SSL(smtp_server, smtp_port) # server_s.set_debuglevel(1) server_s.login(from_addr, password) server_s.sendmail(from_addr, [to_addr], message.as_string()) server_s.quit()
def send_email(sender, sender_passwd, receivers, smtp_server, smtp_port, subject, content=None, file_list=None, debug=None): """" Args: sender: 发送者账户 sender_passwd: 发送者账户密码 receivers: 邮件接收者列表,如 ['*****@*****.**', '*****@*****.**'] smpt_host: SMPT主机 smtp_port: SMPT服务端口(SSL) subject: 邮件主题/标题 content: 正文内容 file_list: 附件的路径列表 Returns: None """ msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = sender msg['To'] = ';'.join(receivers) if content is not None: msg.attach(MIMEText(content, 'plain', 'utf-8')) if file_list is not None: for file in file_list: msg.attach(built_attach(file)) try: s = SMTP_SSL(smtp_server, smtp_port) if debug: s.set_debuglevel(1) s.login(sender, sender_passwd) print('正在向 {} 发送 {}'.format(','.join(receivers), subject)) s.sendmail(sender, receivers, msg.as_string()) s.quit() except smtplib.SMTPException: print('发送邮件时出现错误!') raise
def send_msg(items, item_name): # reply to thread or post an article in the newsgroup SMTPSVR = 'smtp.gmail.com' who = '*****@*****.**' msg = """Subject: Hot items: {item_name} Hello Nat, Here are some interesting items: """.format(item_name=item_name) """ with open('message', 'w') as msg: msg.write('From: YOUR_NAME_HERE <*****@*****.**>\n') msg.write('Newsgroups: %s\n' % group_name) msg.write('Subject: %s\n' % subject) subprocess.call(['nano', 'message']) """ recipients = ['*****@*****.**'] # Add Reciepent Mail item_list = [] for id in items: item_list.append("{name} - {link} - increased by {delta}(From {prev_orders} to {orders})".format(name=items[id]['name'], link=items[id]['link'], delta=items[id]['delta'], prev_orders=items[id]['prev_orders'], orders=items[id]['orders'])) msg += '\n\n'.join(item_list) msg += """ Regards, Ali-Scraper """ try: sendSvr = SMTP_SSL(SMTPSVR, 465) except gaierror: print("Can't connect to %s." % SMTPSVR) exit() sendSvr.ehlo() try: sendSvr.login('*****@*****.**', 'xxxxxx') # Add Your Email ID and Password except SMTPAuthenticationError: print("Invalid SMTP credentials.") exit() errs = sendSvr.sendmail(who, recipients, msg) sendSvr.quit() assert len(errs) == 0, errs print("Email sent!")
def sendEmailByString(self, strSmtpServer, strSendAddr, strPasswd, listToAddr,CCToAddr, strSubject, strContent): # 用字符串来发送邮件 # strSmtpServer: smtp服务器地址 # strSendAddr: 邮件发送地址 # strPasswd: 发送地址的登陆授权码 # listToAddr: 接受邮件的地址,为list集合 # strSubject: 邮件主题 # strContent: 邮件内容字符串类型 message = MIMEText(strContent, "html", "utf-8") message['Subject'] = Header(strSubject, 'utf-8') message['From'] = Header('<%s>' % strSendAddr, 'utf-8') message['To'] = Header(str(listToAddr),'utf-8') if CCToAddr != None: message['Cc'] = Header(str(CCToAddr), 'utf-8') try: smtpObj = SMTP_SSL(strSmtpServer) smtpObj.set_debuglevel(1) smtpObj.ehlo(strSmtpServer) smtpObj.login(strSendAddr, strPasswd) print("登陆成功", 'runLog') if(CCToAddr != None and listToAddr != None) : print("抄送地址不为空") print(listToAddr) print(CCToAddr) print(listToAddr.split(",") + CCToAddr.split(",")) smtpObj.sendmail(strSendAddr, listToAddr.split(",") + CCToAddr.split(","), message.as_string()) smtpObj.quit() elif(CCToAddr == None and listToAddr != None) : print("抄送地址为空") print(listToAddr) print(CCToAddr) smtpObj.sendmail(strSendAddr, listToAddr, message.as_string()) smtpObj.quit() else: print("接收邮件地址为空") print("邮件不发送") except BaseException as e: print(e) print(sys.exc_info()[0]) print("邮件发送失败")
def RegEmail(useremail, username, ticket, usermd5url): mail_info = { "hostname": "smtp.qq.com", "username": "******", "password": "******", "from": "*****@*****.**", "to": "%s" % useremail, "mail_subject": "WelCome to Python Question&Answer", "mail_text": '''<html> <head><meta charset="UTF-8"></head> <body> <h3> WelCome to Python Question&Answer</h3> <br> <p>   用户名:%s</p> <p>   感谢您注册Python问答系统,Click Link:<a href="http://127.0.0.1:8080/activation?email=%s&ticket=%s" style="text-decoration:none">点击激活账号</a></p> <p>   Activate Link:<a href="http://127.0.0.1:8080/activation?email=%s&ticket=%s" style="text-decoration:none">http://127.0.0.1:8080/activation?email=%s&ticket=%s</a></p> <br><img>   如果以上链接无法点击,请联系开发者企鹅:<a href="tencent://message/?uin=350105629&Site=&Menu-=yes" style="text-decoration:none"><img src="http://www.wzsky.net/img2015/uploadimg/20150303/1022549.png" style="height: 42px;vertical-align:middle" alt="icon">350105629</a></p>    ---------------------------- <br><br>    <img src="http://v1.qzone.cc/avatar/201507/15/18/33/55a636e158719534.jpg!200x200.jpg" alt="350105629" style="vertical-align:middle;height: 60px"> Author: Benjamin</p> </body> </html>''' % (username, usermd5url, ticket, usermd5url, ticket, usermd5url, ticket), } smtp = SMTP_SSL(mail_info["hostname"]) smtp.set_debuglevel(1) smtp.ehlo(mail_info["hostname"]) smtp.login(mail_info["username"], mail_info["password"]) msg = MIMEText(mail_info["mail_text"], "html", "utf-8") msg["Subject"] = Header(mail_info["mail_subject"], "utf-8") msg["from"] = mail_info["from"] msg["to"] = mail_info["to"] try: smtp.sendmail(mail_info["from"], mail_info["to"], msg.as_string()) except: pass
def send_email_for(restaurant_name_ids, session): restaurants = session.query(Restaurant).filter( Restaurant.name_id.in_(restaurant_name_ids)).all() passwd = getpass() context = ssl.create_default_context() with SMTP_SSL('smtp.gmail.com', context=context, port=465) as smtp_server: smtp_server.login('*****@*****.**', password=passwd) # message = """ # From: [email protected] # Subject: Test123 # Test 12356 # """ text_restaurants = "\n".join( f'{restaurant.name}-{restaurant.open_hours}' for restaurant in restaurants) text = f""" Hi, this is list of new restaurants..., {text_restaurants} Have a nice day. """ html_restaurants = "\n".join( f'<p>{restaurant.name}-{restaurant.open_hours}</p>' for restaurant in restaurants) html = f""" <h1>Hi</h1> <p>Hi, this is list of new restaurants...,</p> {html_restaurants} <p>Have a nice day!</p> """ print(html_restaurants) content_text = MIMEText(text, 'plane') content_html = MIMEText(html, 'html') message = MIMEMultipart('multipart') message.attach(content_text) message.attach(content_html) message['Subject'] = 'Testing' message['From'] = '*****@*****.**' message['To'] = '*****@*****.**' smtp_server.sendmail('*****@*****.**', ['*****@*****.**'], msg=message.as_string())