to_addrs = ['*****@*****.**', '*****@*****.**'] smtp_server = 'smtp.qq.com' text = '''亲爱的学员,你好! 我是吴枫老师,能遇见你很开心。 希望学习Python对你不是一件困难的事情! 人生苦短,我用Python ''' msg = MIMEText(text, 'plain', 'utf-8') msg['From'] = Header('阿宽') msg['To'] = Header(','.join(to_addrs)) msg['Subject'] = Header('hello python world') #开启发信服务 #以下两行为默认不加密的端口25链接邮箱服务器的方法 '''server = smtplib.SMTP() server.connect(smtp_server, 25) ''' #以下两行为加密SSL端口465链接邮箱服务器的方法 server = smtplib.SMTP_SSL(smtp_server) #如果端口是用SSL加密,请这样写代码。其中server是变量名 server.connect( smtp_server, 465 ) #如果出现编码错误UnicodeDecodeError,你可以这样写:server.connect('smtp.qq.com', 465,'utf-8') #登陆发信邮箱 server.login(username, password) #发送邮件 server.sendmail(from_addr, to_addrs, msg.as_string()) #关闭邮箱服务 server.quit()
parms.to = avoiddups(parms.to) parms.cc = avoiddups(parms.cc) parms.bcc = avoiddups(parms.bcc) # And send the mail. targets = [] if parms.to: targets.extend(parms.to) if parms.cc: targets.extend(parms.cc) if parms.bcc: targets.extend(parms.bcc) if targets and not parms.dryrun: # Connect to the mail server: mailconn = smtplib.SMTP_SSL(parms.mailserver, parms.mailport) mailconn.ehlo() mailconn.login(parms.sender, parms.mailpw) # and send the mail mailconn.sendmail(parms.sender, targets, finalmsg) # and sleep time.sleep(parms.sleep) # If all went well, log the transaction res = [] for which in (parms.to, parms.cc, parms.bcc): for item in which: res.append((item, parms.htmlfile, parms.textfile)) if parms.verbose >= 1:
def main_page(): if current_user.is_authenticated: param = {} session = db_session.create_session() emails = session.query(Emails).all() param['emails'] = emails groups = session.query(Group).filter( current_user.id == Group.admin).all() param['groups'] = [] param['groups_title'] = [] param['groups_id'] = [] for group in groups: param['groups'].append([]) param['groups_title'].append(group.title) param['groups_id'].append(group.id) for member in str(group.members).split(): param['groups'][-1].append([ session.query(Emails).filter( int(member) == Emails.id).first(), group.id ]) param['title'] = 'Главная страница' param['styles'] = os.listdir('static/css/styleForSendMessage/') param['path_for_style'] = '/static/css/styleForSendMessage/' if request.method == 'POST': server = 'smtp.mail.ru' group = request.form['send_message'].split("'")[1] user = current_user.email password = current_user.password_for_email temp_recipients = [ x for x in str( session.query(Group).filter( Group.title == group, Group.admin == current_user.id).first().members).split() ] recipients = [] for x in temp_recipients: recipients.append( session.query(Emails).filter( Emails.id == int(x)).first().email) sender = user subject = 'Рассылка' if request.form['type_message'] == 'html': text = '' html = request.form['text_message'] # filepath = "/var/log/maillog" # basename = os.path.basename(filepath) # filesize = os.path.getsize(filepath) msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = 'Python script <' + sender + '>' msg['To'] = ', '.join(recipients) msg['Reply-To'] = sender msg['Return-Path'] = sender msg['X-Mailer'] = 'Python/' + (python_version()) part_text = MIMEText(text, 'plain') part_html = MIMEText(html, 'html') # part_file = MIMEBase('application', 'octet-stream; name="{}"'.format(basename)) # part_file.set_payload(open(filepath, "rb").read()) # part_file.add_header('Content-Description', basename) # part_file.add_header('Content-Disposition', 'attachment; filename="{}"; size={}'.format(basename, filesize)) # encoders.encode_base64(part_file) else: text = request.form['text_message'] html = ''' <!DOCTYPE html> <html lang="en"> <head> </head> <body> <p>''' + text + '''</p> </body> ''' # filepath = "/var/log/maillog" # basename = os.path.basename(filepath) # filesize = os.path.getsize(filepath) msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = 'Python script <' + sender + '>' msg['To'] = ', '.join(recipients) msg['Reply-To'] = sender msg['Return-Path'] = sender msg['X-Mailer'] = 'Python/' + (python_version()) part_text = MIMEText(text, 'plain') part_html = MIMEText(html, 'html') # part_file = MIMEBase('application', 'octet-stream; name="{}"'.format(basename)) # part_file.set_payload(open(filepath, "rb").read()) # part_file.add_header('Content-Description', basename) # part_file.add_header('Content-Disposition', 'attachment; filename="{}"; size={}'.format(basename, filesize)) # encoders.encode_base64(part_file) if request.files.get('file_message'): img = MIMEImage(request.files['file_message'].read()) msg.attach(img) msg.attach(part_text) msg.attach(part_html) # msg.attach(part_file) mail = smtplib.SMTP_SSL(server) mail.login(user, password) mail.sendmail(sender, recipients, msg.as_string()) mail.quit() return redirect('/') return render_template('send_message.html', **param) else: return redirect('/login')
def email(self): server = smtplib.SMTP_SSL("smtp.gmail.com", 465) server.login(self.username, self.password) server.sendmail(self.username, self.sent_to, self.message) server.quit()
def send(self, recipients=None, **kwargs): """ Sends the email. ``recipients`` List of email addresses of recipients. """ if recipients is None or recipients is []: return log.debug('Getting mail template: %s' % self.template) to = ', '.join(recipients) sender = '%s <%s>' % (pylons.config['debexpo.sitename'], pylons.config['debexpo.email']) c = FakeC(to=to, sender=sender, config=pylons.config, **kwargs) template_file = os.path.join( os.path.dirname(os.path.dirname(__file__)), 'templates/email/%s.mako' % self.template) lookup = TemplateLookup(directories=[os.path.dirname(template_file)]) template = Template( filename=template_file, lookup=lookup, module_directory=pylons.config['app_conf']['cache_dir']) # Temporarily set up routes.util.url_for as the URL renderer used for h.url() in templates pylons.url._push_object(routes.util.url_for) rendered_message = template.render_unicode(_=gettext, h=h, c=c).encode("utf-8") try: # Parse the email message message = email.message_from_string(rendered_message) except email.errors.MessageParseError: # Parsing the message failed, let's send the raw data... message = rendered_message.encode("utf-8") else: # By default, python base64-encodes all UTF-8 text which is annoying. Force quoted-printable email.charset.add_charset('utf-8', email.charset.QP, email.charset.QP, 'utf-8') # Create a new, MIME-aware message new_message = email.mime.text.MIMEText( message.get_payload().decode("utf-8"), "plain", "utf-8") for key in message.keys(): try: contents = message[key].decode("utf-8").split(u" ") except UnicodeDecodeError: # Bad encoding in the header, don't try to do anything more... header = message[key] else: # Do some RFC2047-encoding of the headers. We split on word-boundaries so that # python doesn't encode the whole header in a RFC2047 blob, but only what's # needed. header = email.header.Header() for c in contents: header.append(c) new_message[key] = header # And get that back as a string to pass onto sendmail message = new_message.as_string() pylons.url._pop_object() if self.ssl: log.debug('Starting SMTP_SSL session to %s:%s' % (self.server, self.port)) session = smtplib.SMTP_SSL(self.server, self.port) else: log.debug('Starting SMTP session to %s:%s' % (self.server, self.port)) session = smtplib.SMTP(self.server, self.port) if self.auth: log.debug('Authentication requested; logging in') session.login(self.auth['username'], self.auth['password']) log.debug('Sending email to %s' % ', '.join(recipients)) result = session.sendmail(pylons.config['debexpo.email'], recipients, message) if result: # Something went wrong. for recipient in result.keys(): log.critical( 'Failed sending to %s: %s, %s' % (recipient, result[recipient][0], result[recipient][1])) else: log.debug('Successfully sent')
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email import encoders # 보내는 사람 정보 me = "*****@*****.**" my_password = "******" # 로그인하기 s = smtplib.SMTP_SSL('smtp.gmail.com') s.login(me, my_password) # 받는 사람 정보 you = "*****@*****.**" # 메일 기본 정보 설정 msg = MIMEMultipart('alternative') msg['Subject'] = "이것이 제목이다" msg['From'] = me msg['To'] = you # 메일 내용 쓰기 content = "메일 내용" part2 = MIMEText(content, 'plain') msg.attach(part2) part = MIMEBase('application', "octet-stream") with open("articles.xlsx", 'rb') as file: part.set_payload(file.read())
msg['To'] = _formataddr('777 %s' % to) msg['Subject'] = Header('嵌入图片测试', 'utf-8').encode() with open('./images/a.jpg', 'rb') as f: mine = MIMEBase('image', 'jpg', filename='send.jpg') mine.add_header('Content-Disposition', 'attachment', filename='send.jpg') mine.add_header('Content-ID', '<0>') mine.add_header('X-Attachment-Id', '0') mine.set_payload(f.read()) encoders.encode_base64(mine) msg.attach(mine) #低版本显示 msg.attach(MIMEText('send a msg', 'plain', 'utf-8')) #高版本显示 msg.attach( MIMEText( '<html><body><h2><a href="https://www.baidu.com">百度</a><img src="cid:0"><h2><h5>嵌入图片测试aaaa<h5></body></html>', 'html', 'utf-8')) #QQ邮箱采用https协议 server = smtplib.SMTP_SSL(smtp_server, port) # #建立安全连接,https # server.starttls() server.set_debuglevel(1) server.login(msg_from, password) server.sendmail(msg_from, [to], msg.as_string()) server.quit()
def send_alert(config, message): with smtplib.SMTP_SSL(config['smtp_server'], config['SMTP_SSL_port'], context=context) as server: server.login(config['smtp_user'], config['smtp_password']) server.sendmail(config['smtp_user'], config['alert_recipient'], message)
def __change_user_password_query(self): """ This function will execute the query for resetting the user password :return: Json object """ try: with transaction.atomic(): if DEVELOPMENT: self._psql_session.execute( CHECK_AUTHENTICATION_QUERY.format( self.loggedin_userid_details[LOGIN_ID])) else: self._psql_session.execute( CHECK_AUTHENTICATION_QUERY.format( self.loggedin_userid_details[LOGIN_ID])) if not self._psql_session.rowcount: return JsonResponse({MESSAGE_KEY: USERNAME_NOT_REGISTERED}, status=HTTP_400_BAD_REQUEST) result_set = self._psql_session.fetchall() Permission = pd.DataFrame(result_set) self._psql_session.execute( CHECK_AUTHENTICATION_QUERY.format( self._request_payload[LOGIN_ID])) admin = pd.DataFrame(self._psql_session.fetchall()) if not admin.empty: check_admin = admin[USER_TYPE].iloc[0] receiver = admin['email_id'].iloc[0] else: return JsonResponse( {MESSAGE_KEY: "USER IS NOT REGISTER WITH US"}) if Permission[USER_TYPE].iloc[ 0] == 'Super Admin' or check_admin == 'Admin' or check_admin == 'Super ' \ 'Admin': self._psql_session.execute(CHECK_LOGIN_ID) loginids = self._psql_session.fetchall() login_ids = pd.DataFrame(loginids) log_in_id = list(login_ids["login_id"]) if self._request_payload[LOGIN_ID] in log_in_id: obj = HashingSalting() if obj.check_password( self._request_payload[USERPASSWORD_KEY], Permission[SALT_KEY].iloc[0], Permission[USERPASSWORD_KEY].iloc[0]): hash_value, salt_value = obj.get_hashed_password( self._request_payload[USERFUTUREPASSWORD_KEY]) if ENV: self._psql_session.execute( CHANGE_RESET_USER_PASSWORD_QUERY.format( SALT_KEY, salt_value, USERPASSWORD_KEY, hash_value, LOGIN_ID, self._request_payload[LOGIN_ID])) else: self._psql_session.execute( CHANGE_RESET_USER_PASSWORD_QUERY.format( SALT_KEY, salt_value, USERPASSWORD_KEY, hash_value, LOGIN_ID, self._request_payload[LOGIN_ID])) # s = smtplib.SMTP('smtp.gmail.com', 587) # s.starttls() # sender = '*****@*****.**' # s.login(sender, 'Mdevendra@1996') # receiver_mail = receiver # msg = MIMEMultipart('alternative') # msg['Subject'] = "Password" # msg['From'] = sender # msg['To'] = receiver_mail # context = """Hi.\n Here is the you are Password .\n {}""".format( # self._request_payload[USERFUTUREPASSWORD_KEY]) # part1 = MIMEText(context, 'plain') # msg.attach(part1) # s.sendmail(sender, '*****@*****.**', msg.as_string()) port = 465 # For SSL smtp_server = "smtpout.ingenero.com" context = ssl.create_default_context() with smtplib.SMTP_SSL(smtp_server, port, context=context) as server: print( server.login('*****@*****.**', 'Ap5sn%k*20')) msg = MIMEMultipart('alternative') msg['Subject'] = "Reset Password" msg['From'] = '*****@*****.**' msg['To'] = '*****@*****.**' context = """Hi.\n Here is your password .\n {}""".format( self. _request_payload[USERFUTUREPASSWORD_KEY]) part1 = MIMEText(context, 'plain') msg.attach(part1) server.sendmail('*****@*****.**', '*****@*****.**', msg.as_string()) server.quit() if self._psql_session.rowcount: return JsonResponse({ MESSAGE_KEY: "PASSWORD UPDATED SUCCESSFULLY AND PASSWORD SENT TO " "MAIL" }) return JsonResponse({MESSAGE_KEY: RESET_ERROR}, status=HTTP_400_BAD_REQUEST) return JsonResponse({MESSAGE_KEY: PASSWORD_WRONG}, status=HTTP_400_BAD_REQUEST) return JsonResponse( {MESSAGE_KEY: "USER IS NOT REGISTER WITH US"}) else: return JsonResponse({ MESSAGE_KEY: "NON ADMIN USER IS NOT ACCESS TO CHANGE PASSWORD" }) except IntegrityError as e: log_error("Exception due to : %s" + str(e)) return json_InternalServerError except Exception as e: log_error("Exception due to : %s" + str(e)) return json_InternalServerError
#This is first method. You can use either one # import smtplib # from email.message import EmailMessage # msg=EmailMessage() # msg['Subject']="Training Invitaion" # msg['From']="*****@*****.**" # msg['To']="*****@*****.**" # msg.set_content("This is for practice purpose") # server=smtplib.SMTP_SSL("smtp.gmail.com",465) # same for all # server.login("your Email ID","Your Password") # server.send_message(msg) # # server.sendmail("*****@*****.**", "*****@*****.**", "hi how are u") # server.quit() import smtplib server = smtplib.SMTP_SSL("smtp.gmail.com", 465) # same for all server.login("Your email Id", "Your password") server.sendmail("*****@*****.**", "*****@*****.**", "Write some message") server.quit()
for row in sub.sub_rows: absolute_save_path = path_concat(save_path, url_to_file_name(row.url())) if not(os.path.isfile(absolute_save_path)): res = 1 while res == 1: res = subprocess.call([tabcmd, 'export', row.url(), '-f', absolute_save_path, '--png', '--pagesize', 'unspecified', '--width', '1200', '--height', '800', '--timeout', '300', '--no-certcheck']) row.saved_path = absolute_save_path # ################################################################ #Sending Emails ################################################################ if not (args.skip_email): if SMTP_SSL: smtp_conn = smtplib.SMTP_SSL(smtp_server, smtp_server_port) smtp_conn.login(SMTP_USERNAME, SMTP_PASSWORD) else: smtp_conn = smtplib.SMTP(smtp_server, smtp_server_port) for email in sub.unique_emails(): # Overrides ################################################################ if args.file_override: filenames = [args.file_override] else: filenames = [email_row.saved_path for email_row in filter(lambda sub_row: sub_row.csv_dict['Email'] == email, sub.sub_rows)] if args.to_override: message_to = args.to_override else:
import smtplib, ssl port = 465 smtp_server = "smtp.gmail.com" sender_email = "*****@*****.**" receiver_email = "*****@*****.**" password = input("Enter your password") message = """ subject: Hi there This message is sent from python.""" context = ssl.create_default_context() with smtplib.SMTP_SSL(smtp_server, port, context=context) as server: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, message)
def connect(self, host=None, port=None, user=None, password=None, encryption=None, smtp_debug=False, mail_server_id=None): """Returns a new SMTP connection to the given SMTP server. When running in test mode, this method does nothing and returns `None`. :param host: host or IP of SMTP server to connect to, if mail_server_id not passed :param int port: SMTP port to connect to :param user: optional username to authenticate with :param password: optional password to authenticate with :param string encryption: optional, ``'ssl'`` | ``'starttls'`` :param bool smtp_debug: toggle debugging of SMTP sessions (all i/o will be output in logs) :param mail_server_id: ID of specific mail server to use (overrides other parameters) """ # Do not actually connect while running in test mode if getattr(threading.currentThread(), 'testing', False): return None mail_server = smtp_encryption = None if mail_server_id: mail_server = self.sudo().browse(mail_server_id) elif not host: mail_server = self.sudo().search([], order='sequence', limit=1) if mail_server: smtp_server = mail_server.smtp_host smtp_port = mail_server.smtp_port smtp_user = mail_server.smtp_user smtp_password = mail_server.smtp_pass smtp_encryption = mail_server.smtp_encryption smtp_debug = smtp_debug or mail_server.smtp_debug else: # we were passed individual smtp parameters or nothing and there is no default server smtp_server = host or tools.config.get('smtp_server') smtp_port = tools.config.get('smtp_port', 25) if port is None else port smtp_user = user or tools.config.get('smtp_user') smtp_password = password or tools.config.get('smtp_password') smtp_encryption = encryption if smtp_encryption is None and tools.config.get('smtp_ssl'): smtp_encryption = 'starttls' # smtp_ssl => STARTTLS as of v7 if not smtp_server: raise UserError( (_("Missing SMTP Server") + "\n" + _("Please define at least one SMTP server, " "or provide the SMTP parameters explicitly."))) if smtp_encryption == 'ssl': if 'SMTP_SSL' not in smtplib.__all__: raise UserError( _("Your actpy Server does not support SMTP-over-SSL. " "You could use STARTTLS instead. " "If SSL is needed, an upgrade to Python 2.6 on the server-side " "should do the trick.")) connection = smtplib.SMTP_SSL(smtp_server, smtp_port) else: connection = smtplib.SMTP(smtp_server, smtp_port) connection.set_debuglevel(smtp_debug) if smtp_encryption == 'starttls': # starttls() will perform ehlo() if needed first # and will discard the previous list of services # after successfully performing STARTTLS command, # (as per RFC 3207) so for example any AUTH # capability that appears only on encrypted channels # will be correctly detected for next step connection.starttls() if smtp_user: # Attempt authentication - will raise if AUTH service not supported # The user/password must be converted to bytestrings in order to be usable for # certain hashing schemes, like HMAC. # See also bug #597143 and python issue #5285 smtp_user = pycompat.to_native(ustr(smtp_user)) smtp_password = pycompat.to_native(ustr(smtp_password)) connection.login(smtp_user, smtp_password) return connection
msg = MIMEMultipart("alternative") msg["Subject"] = subject msg["From"] = "Prank email spammer <" + sender + ">" msg["To"] = ", ".join(recipients) msg["Reply-To"] = sender msg["Return-Path"] = sender msg["X-Mailer"] = "Prank email spammer" part_text = MIMEText(text, "plain") part_html = MIMEText(html, "html") msg.attach(part_text) msg.attach(part_html) mail = smtplib.SMTP_SSL(server) #print("Инфа - ", user, "_", password, "_", server) mail.login(user, password) for i in range(email_count): mail.sendmail(sender, recipients, msg.as_string()) print("Письмо №", (i + 1), " отправлено!") print("Все письма успешно отправлены!") mail.quit() except: print("Что-то пошло не так!") #print()
fp = open('img/naramispresso-logotext-bw.png', 'rb') image1 = MIMEImage(fp.read()) fp.close() image1.add_header('Content-ID', '<naramispresso-logotext-bw>') msg.attach(image1) fp = open('img/naramispresso-mail-header.jpeg', 'rb') image2 = MIMEImage(fp.read()) fp.close() image2.add_header('Content-ID', '<naramispresso-mail-header>') msg.attach(image2) try: print('Sending bill...') ## Mail sending smtp_server = smtplib.SMTP_SSL( params['mail_server']['address'], params['mail_server']['port']) smtp_server.ehlo() # smtp_server.starttls() smtp_server.login(params['mail_server']['login'], params['mail_server']['password']) smtp_server.sendmail(msg['From'], msg['To'], msg.as_string()) smtp_server.sendmail(msg['From'], params['contact_mail'], msg.as_string()) smtp_server.close() print(' ...OK') except Exception as e: print(e) print('Somehting went wrong when trying to send the mails.') csv_file.close()
else: receivers = toEmails[:NUMBER_OF_EMAILS] else: print "No more receiver email!" break # Extract usename and password of sender, used to login to Gmail senderUser = sender.split(' ')[0].strip() senderPass = sender.split(' ')[1].strip() email["Subject"] = "Mời tham gia khóa học lập trình Python" email["From"] = senderUser email["To"] = ", ".join(receivers) # Login to Gmail and send emails using above senders and receivers serverSSL = smtplib.SMTP_SSL("smtp.gmail.com", 465) serverSSL.ehlo() serverSSL.login(senderUser, senderPass) # SSL does not support TLS, no need to call serverSSL.starttls() serverSSL.sendmail(senderUser, receivers, email.as_string()) serverSSL.close() print "Successful sending emails from %s to all receivers!" % ( senderUser) # Remove emails already used to send or receive fromEmails = fromEmails[1:] toEmails = toEmails[NUMBER_OF_EMAILS:] sleep(5000)
driver.find_element_by_name("submit").click() driver.close() except: sender = '*****@*****.**' receivers = ['*****@*****.**'] message = """From: From Person <*****@*****.**> To: To Person <*****@*****.**> Subject: SMTP e-mail test code error code error. """ try: print("trying host and port...") smtpObj = smtplib.SMTP_SSL('smtp.gmail.com', 465) smtpObj.login("*****@*****.**", "killbill12345") print("sending mail...") smtpObj.sendmail(sender, receivers, message) print("Succesfully sent email") except smtplib.SMTPException: print("Error: unable to send email") import traceback traceback.print_exc()
def forgot(clientsock, addr, mailEmail, mailPassword): # Sets up the register connection logger = logging.getLogger("Forgot") clientsock.send("FORGOT\n".encode()) data = clientsock.recv(1024) ip = addr[0] username = data.decode().rstrip() # Connects to the db conn = sqlite3.connect('serverFiles/server.db') conn.cursor().execute( "CREATE TABLE IF NOT EXISTS tbl_users (user TEXT PRIMARY KEY, pass TEXT, email TEXT, last_logged TEXT, " "admin TEXT);") # Used to get the email for later c = conn.cursor() c.execute("SELECT * FROM tbl_users WHERE user = ? LIMIT 1", (username,)) row = c.fetchone() # If doesn't exist, it adds it to the db if row is None: clientsock.send("DENY\n".encode()) logger.info("NO SUCH USER %s %s" % (username, ip)) else: # Gets the users email email = row[2] # Connects to the db, creates table if not exist conn = sqlite3.connect('serverFiles/server.db') conn.cursor().execute("CREATE TABLE IF NOT EXISTS tbl_reset_codes (reset_code TEXT PRIMARY KEY, user TEXT, " "FOREIGN KEY(user) REFERENCES tbl_users(user));") # Connects to the table to see if there is already a code c = conn.cursor() c.execute("SELECT reset_code FROM tbl_reset_codes WHERE user = ? LIMIT 1", (username,)) checkCode = c.fetchone() # Creates a randomly generated code and adds it to a global dictionary for later use rawCode = uuid.uuid4().hex resetCode = hashlib.sha256(rawCode.encode()).hexdigest() # If there isn't a code for the user, add one if checkCode is None: c.execute("INSERT INTO tbl_reset_codes(reset_code, user) VALUES(?, ?)", (resetCode, username)) conn.commit() # Else delete the old code, and set the new one else: c.execute("DELETE FROM tbl_reset_codes WHERE user = ?", (username,)) conn.commit() c.execute("INSERT INTO tbl_reset_codes(reset_code, user) VALUES(?, ?)", (resetCode, username)) conn.commit() # Sets up email contents sent_from = mailEmail to = [email] subject = 'IRC Reset Code' body = 'Here is your reset code for user %s:\n%s' % (username, resetCode) # Orders the strings to be sent email_text = """From: %s\nTo: %s \nSubject: %s\n\n%s """ % (sent_from, ", ".join(to), subject, body) # Attempt to send the email try: # Sets up the connection and sends the email server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() server.login(mailEmail, mailPassword) server.sendmail(sent_from, to, email_text) server.close() # If it was successful, these lines run clientsock.send("SENT\n".encode()) logger.info("FORGOT SENT %s %s %s" % (ip, username, email)) # If fails, send back it failed. except: clientsock.send("FAIL\n".encode()) logger.error("FORGOT SENT FAIL %s %s %s" % (ip, username, email)) clientsock.close() # print(colored(repr(addr) + ": Forgot connection closed", 'red')) logger.info(repr(addr) + ": Forgot connection closed")
from_addr = "@qq.com" # 此处密码是经过申请设置后的授权码,不是邮箱秘密 from_pwd = "f" # 收件人信息 # 此处使用qq邮箱 to_addr = "@qq.com" # 输入SMTP服务器地址 # 此处根据不同的邮件服务商有不同的值 # 现在基本任何一家邮件服务商,如果采用第三方发邮件,都需要开启授权选择 # 腾讯qq邮箱锁在的stmp地址是 smtp.qq.com smtp_srv = "smtp.qq.com" try: # 两个参数 # 第一个是服务器地址,但一定shibytes格式,所以需要编码 # 第二个参数是服务器的接受范文端口 srv = smtplib.SMTP_SSL(smtp_srv.encode(), 465) # SMTP协议默认端口25 # 登陆邮箱发送 srv.login(from_addr, from_pwd) # 发送邮件 # 三个参数 # 1. 发送地址 # 2. 接收地址,必须是list形式 # 3. 发送内容,作为字符串发送 srv.sendmail(from_addr, [to_addr], msg.as_string()) srv.quit() except Exception as e: print(e)
f = open(yamlPath,'r',encoding='utf-8') #文件读取 cont = f.read() #用load方法转字典 x = yaml.load(cont, Loader=yaml.FullLoader) # ----------1.跟发件相关的参数------ # smtpserver = "smtp.163.com" # 发件服务器 smtpserver = "smtp.qq.com" port = 465 # 端口 sender = x['user2'] # 账号 psw = x['pwd'] # 密码 receiver = x['user1'] # 接收人 # ----------2.编辑邮件的内容------ subject = "这个是主题QQ" body = '<p>这个是发送的QQ邮件</p>' # 定义邮件正文为html格式 msg = MIMEText(body, "html", "utf-8") msg['from'] = sender msg['to'] = receiver msg['subject'] = subject # ----------3.发送邮件------ # smtp = smtplib.SMTP() # smtp.connect(smtpserver) # 连服务器 smtp = smtplib.SMTP_SSL(smtpserver, port) smtp.login(sender, psw) # 登录 smtp.sendmail(sender, receiver, msg.as_string()) # 发送 smtp.quit() # 关闭
# Python code to send email to a list of # emails from a spreadsheet # import the required libraries import pandas as pd import smtplib # email and password your_email = "your email" your_password = "******" #Login in server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() server.login(your_email, your_password) #Read the Exel email_list = pd.read_excel('Name of the Exel.xls') #making 2 list with the names and the emails names = email_list['NAME'] emails = email_list['EMAIL'] for i in range(len(emails)): name = names[i] email = emails[i] print(emails[i]) mail_subject = 'subject' #Subject mail_message_body = 'message body' #message body
def send(): port = 465 # standard port for SMTP over SSL smtp_server = "smtp.gmail.com" correct_login = False send = 0 name = prompt_name() residency = prompt_residency() recv = prompt_recipients() subject, message = prompt_email(name, residency) # while True: try: # create a secure SSL context context = ssl.create_default_context() # open smtplib, a client object to send emails. -> take in server and port to send from with smtplib.SMTP_SSL(smtp_server, port, context=context) as server: while correct_login is False: try: src_email, password = prompt_login() server.login(src_email, password) correct_login = True except: print( "\033[1;31;48mIncorrect email or password. Please try again" ) print("\033[1;37;48m") if correct_login: # Take info from recipients file while recv: recipient = recv.pop() recv_name = recipient[0] location = recipient[1] dst_email = recipient[2] police_budget = recipient[3] total_budget = recipient[4] police_budget_int = int(police_budget.replace(",", "")) total_budget_int = int(total_budget.replace(",", "")) percent = round( 100 * (police_budget_int / total_budget_int), 2) msg = EmailMessage() if len(subject) > 0: msg['Subject'] = subject else: msg['Subject'] = messages.gen_subject() msg['From'] = src_email msg['To'] = dst_email message = message.replace("[POLICE-BUDGET]", police_budget) message = message.replace("[TOTAL-BUDGET]", total_budget) message = message.replace("[PERCENT]", str(percent)) message = message.replace("[CITY-NAME]", location) if residency.lower() != location.lower(): message = message.replace( " and I am from " + residency + ".", " and") message = message.replace("member of this community", "citizen") body = "Dear " + recv_name + " of " + location + ",\n\n" + message msg.set_content(body) print(msg.as_string()) server.send_message(msg) send += 1 # break except smtplib.SMTPException: print("Unexpected error... trying again in 10 seconds.") print("Are you running this program in terminal?") time.sleep(10) print_barrier() print(f'\nSuccessfully sent {send} emails!\n') print_barrier()
def _get_smtp_connection(host: str, port: int, timeout: int, with_ssl: bool) -> smtplib.SMTP: return (smtplib.SMTP_SSL(host=host, port=port, timeout=timeout) if with_ssl else smtplib.SMTP(host=host, port=port, timeout=timeout))
def sendHTMLEmail(sender_email, recipient_email, subject, htmlTemplate, textTemplate, c={}): funcname = f'({__filename}) sendHTMLEmail(sender_email={sender_email}, recipient_email={recipient_email}, subject={subject}, htmlTemplate=..., textTemplate=..., c={c})' logenter(funcname, simpleprint=False, tprint=True) # Create message container - the correct MIME type is multipart/alternative. loginfo(funcname, '... 00', simpleprint=True) msg = MIMEMultipart('alternative') loginfo(funcname, '... 01', simpleprint=True) msg['Subject'] = subject.encode('utf-8') loginfo(funcname, '... 02', simpleprint=True) msg['From'] = sender_email.encode('utf-8') loginfo(funcname, '... 03', simpleprint=True) msg['To'] = recipient_email.encode('utf-8') loginfo(funcname, '... 04', simpleprint=True) #msg["Date"] = email.Utils.formatdate(localtime=True) # Create the body of the message (a plain-text and an HTML version). #text = render_template(textTemplate, c=c) text = textTemplate loginfo(funcname, '... 05', simpleprint=True) #html = render_template(htmlTemplate, c=c) html = htmlTemplate loginfo(funcname, '... 06', simpleprint=True) # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(text, 'plain') loginfo(funcname, '... 07', simpleprint=True) part2 = MIMEText(html, 'html') loginfo(funcname, '... 08', simpleprint=True) # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. msg.attach(part1) loginfo(funcname, '... 09', simpleprint=True) msg.attach(part2) loginfo(funcname, '... 10', simpleprint=True) # Send the message via local SMTP server. #s = smtplib.SMTP('localhost') # sendmail function takes 3 arguments: sender's address, recipient's address # and message to send - here it is sent as one string. #s.sendmail(me, you, msg.as_string()) #s.quit() server = smtplib.SMTP_SSL(SES_SERVER, SES_PORT) loginfo(funcname, '... 11', simpleprint=True) server.set_debuglevel(1) loginfo(funcname, '... 12', simpleprint=True) server.ehlo() loginfo(funcname, '... 13', simpleprint=True) server.login(SES_LOGIN, SES_PASSWORD) loginfo(funcname, '... 14', simpleprint=True) server.sendmail(sender_email, [recipient_email], msg.as_string()) #server.sendmail(sender_email, [recipient_email], msg) #server.sendmail(sender_email, recipient_email, msg) #strMsgEncode = getStrEncodeUTF8(msg) #server.sendmail(sender_email, recipient_email, strMsgEncode) #server.sendmail(sender_email, [recipient_email], "msg.as_string()") loginfo(funcname, '... 15', simpleprint=True) server.quit() loginfo(funcname, '... 16', simpleprint=True) return True
<body> <div style=''> <h2 align='center' style='font-family:Arial; color:#e6e6e6; background:#a22222; padding:10px 0 10px 0;'>RiftsPoPo</h2> <div> <h5 style='color:#565656; font-size:24px;'>CÓDIGO DE CORFIRMAÇÃO: {codigo}</h5> </div> <div> <img style='position:relative; left:340px;' src='https://vignette.wikia.nocookie.net/leagueoflegends/images/7/78/Rengar_Render.png/revision/latest?cb=20131020145558&path-prefix=pt-br' width='256px' alt='sandney mito ahuahuah'> </div> </div> </body> </html> """ # Turn these into plain/html MIMEText objects part1 = MIMEText(text, "plain") part2 = MIMEText(html, "html") # Add HTML/plain-text parts to MIMEMultipart message # The email client will try to render the last part first message.attach(part1) message.attach(part2) # Create secure connection with server and send email context = ssl.create_default_context() with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, message.as_string())
import smtplib from email.message import EmailMessage import getpass password = getpass.getpass('what`s your password? : ') email_list = ['*****@*****.**', '*****@*****.**'] msg = EmailMessage() msg['Subject'] = "안녕 난 거니야" msg['From'] = "*****@*****.**" msg['To'] = "*****@*****.**" #msg.set_content('') msg.add_alternative(''' <h1>안녕하세요.</h1> <p>저는 송건희입니다.</p> ''', subtype="html") #string을 여러 줄 거쳐서 보낼 때 ``` 사용함. subtype="html" : html 형식 사용. #h1 : 글자 크고 진하게 #p : smtp_url = 'smtp.naver.com' smtp_port = 465 s = smtplib.SMTP_SSL(smtp_url, smtp_port) #smptlib.SMPT_SLL()은 보안 연결을 위해 하는 작업임. s.login("*****@*****.**", password) #s.login(id, pw) s.send_message(msg)
def sendMail(Debug_Email, Debug_Password, subject, text, *attachmentFilePaths): import smtplib from email.mime.multipart import MIMEMultipart from email.MIMEText import MIMEText #from email.MIMEImage import MIMEImage #from email import Encoders TypeError = "" extra = "" gmailUser = "" count = 0 SMTP_SSL = False #recipient = '*****@*****.**' #if 1 + 1 == 2: try: dp = xbmcgui.DialogProgress() dp.create(addonString(32095), addonString(10), "") while count == 0 and not dp.iscanceled() and not xbmc.abortRequested: if '@gmail.com' in Debug_Email: mailServer = smtplib.SMTP('smtp.gmail.com', 587) #, timeout=20 elif '@walla.com' in Debug_Email or '@walla.co.il' in Debug_Email: mailServer = smtplib.SMTP_SSL('out.walla.co.il', 587) SMTP_SSL = True elif '@yahoo.com' in Debug_Email or '@yahoo.co.uk' in Debug_Email: try: mailServer = smtplib.SMTP_SSL('smtp.mail.yahoo.com', 465) except: mailServer = smtplib.SMTP_SSL('smtp.mail.yahoo.com', 587) SMTP_SSL = True else: notification_common('27') count += 1 xbmc.sleep(500) msg = MIMEMultipart() msg['From'] = Debug_Email msg['To'] = recipient msg['Subject'] = subject msg.attach(MIMEText(text)) dp.update(10, addonString(32094), addonString(32093) % ("1", "4")) if str(attachmentFilePaths) != "('',)": for attachmentFilePath in attachmentFilePaths: msg.attach(getAttachment(attachmentFilePath)) else: pass #msg.attach(getAttachment(addonIcon)) dp.update(20, addonString(32094), addonString(32093) % ("1", "4")) #mailServer.ehlo() if SMTP_SSL == False: mailServer.starttls() dp.update(30, addonString(32094), addonString(32093) % ("2", "4")) mailServer.ehlo() dp.update(40, addonString(32094), addonString(32093) % ("3", "4")) mailServer.login(Debug_Email, Debug_Password) dp.update(50, addonString(32094), addonString(32093) % ("3", "4")) mailServer.sendmail(Debug_Email, recipient, msg.as_string()) mailServer.quit() count += 1 dp.update(100, addonString(32094), addonString(32093) % ("4", "4")) notification(addonString(74483), localize(20186), "", 2000) returned = 'ok' '''---------------------------''' #try: test = 'test' except Exception, TypeError: try: mailServer.quit() except: pass notification( addonString(32092).encode('utf-8'), str(TypeError), "", 2000) if "535, '5.7.8 Username and Password not accepted." in TypeError: '''gmail''' returned = 'skip' elif "552," in TypeError and "5.2.3 Your message exceeded Google" in TypeError: '''gmail''' returned = 'error' elif "534, '5.7.14" in TypeError: '''gmail''' returned = 'skip' elif 'Server not connected' in TypeError: '''outlook''' returned = 'skip' elif 'getaddrinfo failed' in TypeError: returned = 'skip2' elif 'Connection unexpectedly closed' in TypeError: '''outlook''' returned = 'skip' else: returned = 'skip' '''---------------------------'''
import smtplib from email.mime.text import MIMEText # conexão com os servidores do google smtp_ssl_host = 'smtp.gmail.com' smtp_ssl_port = 465 # username ou email para logar no servidor username = '******' password = '******' from_addr = '*****@*****.**' to_addrs = ['*****@*****.**'] # a biblioteca email possuí vários templates # para diferentes formatos de mensagem # neste caso usaremos MIMEText para enviar # somente texto message = MIMEText('Hello World') message['subject'] = 'Hello' message['from'] = from_addr message['to'] = ', '.join(to_addrs) # conectaremos de forma segura usando SSL server = smtplib.SMTP_SSL(smtp_ssl_host, smtp_ssl_port) # para interagir com um servidor externo precisaremos # fazer login nele server.login(username, password) server.sendmail(from_addr, to_addrs, message.as_string()) server.quit()
import smtplib, ssl from email.message import EmailMessage smtp_server = "smtp.gmail.com" port = 465 # For SSL user = "******" password = "******" from_mail = user to_mails = ["*****@*****.**"] msg = EmailMessage() msg.set_content("hello, send from python smtplib, ssl, and email") msg['Subject'] = 'Automail from Python smtplib, ssl and email' msg['From'] = from_mail msg['To'] = ", ".join(to_mails) # Create a secure SSL context context = ssl.create_default_context() with smtplib.SMTP_SSL(smtp_server, port, context=context, timeout=60) as server: server.set_debuglevel(1) server.login(user, password) server.send_message(msg) print("MSG Send!") server.quit()
#!/usr/bin/python3 # When using gmail make sure you turn on "allow less secure appps" # you can do that here: https://myaccount.google.com/lesssecureapps import smtplib content = "The message content" Sender = "*****@*****.**" Receiver = "*****@*****.**" Password = "******" message = """From: [email protected] To: <*****@*****.**> Subject: SMTP e-mail test {0} """.format(content) # if the sender is a gmail account , here are to configurations s = smtplib.SMTP_SSL("smtp.gmail.com", 465) s.login(Sender, Password) s.sendmail(Sender, Receiver, message) s.quit()