def __sendAdminBounceNotice(self, member, msg, did=_('disabled')): # BAW: This is a bit kludgey, but we're not providing as much # information in the new admin bounce notices as we used to (some of # it was of dubious value). However, we'll provide empty, strange, or # meaningless strings for the unused %()s fields so that the language # translators don't have to provide new templates. siteowner = Utils.get_site_email(self.host_name) text = Utils.maketext('bounce.txt', { 'listname': self.real_name, 'addr': member, 'negative': '', 'did': did, 'but': '', 'reenable': '', 'owneraddr': siteowner, }, mlist=self) subject = _('Bounce action notification') umsg = Message.UserNotification(self.GetOwnerEmail(), siteowner, subject, lang=self.preferred_language) # BAW: Be sure you set the type before trying to attach, or you'll get # a MultipartConversionError. umsg.set_type('multipart/mixed') umsg.attach( text.MIMEText(text, _charset=Utils.GetCharSet(self.preferred_language))) if isinstance(msg, str): umsg.attach(text.MIMEText(msg)) else: umsg.attach(message.MIMEMessage(msg)) umsg.send(self)
def _create_message(part, subtype, filename): msg = (text.MIMEText(part, _subtype=subtype) if subtype else text.MIMEText(part)) if filename: msg.add_header('Content-Disposition', 'attachment', filename=filename) return msg
def SendEmail(user, psw, subject, AnnexList, toaddr, content, emailsrv): # print subject try: #创建一个带附件的实例 msg = multipart.MIMEMultipart() #构造附件 for Annex in AnnexList: annexfile = open(Annex, 'rb') annexdata = annexfile.read() annexfile.close() att = text.MIMEText(annexdata, 'base64', 'gb2312') att['Content-Type'] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename="%s"' % ( os.path.basename(Annex)) msg.attach(att) #构造正文 att = text.MIMEText(content, 'base64', 'gb2312') att['Content-Type'] = 'text/plain' att["Content-Transfer-Encoding"] = '7bit' msg.attach(att) #加邮件头 msg['to'] = toaddr msg['from'] = user msg['subject'] = header.Header(subject, 'gb2312') s = smtplib.SMTP(emailsrv) s.login(user, psw) s.sendmail(msg['from'], toaddr, msg.as_string()) s.quit() except: return False, "%s" % traceback.format_exc() return True, ""
def email_file(self,filename=None,showname=None,img=None,body=None,subject=None,sendername=None): #此处直接定义一个发送图片+文件的方法 self.text_obj = multipart.MIMEMultipart() # 附件形式 # 添加一个文件 if filename: with open(filename, 'rb') as fo: fo_str = fo.read() attr = text.MIMEText(fo_str, _charset='utf-8') attr["Content-Type"] = 'application/octet-stream' if not showname: showname=os.path.basename(filename) # attr['Content-Disposition'] = 'attachment; filename=%s'%showname # 没有这个不显示附件位置··WWWW是名称,可以参数格式化 attr.add_header('Content-Disposition', 'attachment', filename=('gbk', '', showname)) self.text_obj.attach(attr) if not subject: subject='附件--%s'%showname if img and body: self.text_obj.attach(text.MIMEText(body, 'html', 'utf-8')) # 显示一个图片 with open(img, 'rb') as fo: im_str = fo.read() attr = image.MIMEImage(im_str) # attr.add_header('Content-ID', '<image1>') #指定图片 img_id = re.findall(r'cid:(\w+).*', body)[0] attr['Content-ID'] = '<%s>'%img_id # 这个是和body中的image1一致 self.text_obj.attach(attr) if not subject: subject='图片--%s'%(os.path.basename(img)) self.__email_conf(subject,sendername) self.__send_eamil()
def execute(self, *args, **kwargs): userdata = mime_multipart.MIMEMultipart() rabbit_nodes = { "rabbit-node-%d" % i: kwargs["%s%d" % (self.node_ip_prefix, i)] for i in range(self.node_count) } cloud_config = self.cloud_config_template.render( node_name=kwargs['node_name']) sub_message = mime_text.MIMEText(cloud_config, 'cloud-config', sys.getdefaultencoding()) sub_message.add_header('Content-Disposition', 'attachment; filename="cloud_config"') userdata.attach(sub_message) userdata_inputs = { 'rabbit_nodes': rabbit_nodes, 'erlang_cookie': kwargs['erlang_cookie'], 'default_rabbit_user': kwargs['default_rabbit_user'], 'default_rabbit_pass': kwargs['default_rabbit_pass'], 'cluster_id': kwargs['cluster_id'], } script = self.userdata_template.render(userdata_inputs) sub_message = mime_text.MIMEText(script, 'x-shellscript', sys.getdefaultencoding()) sub_message.add_header('Content-Disposition', 'attachment; filename="setup_rabbitmq.sh"') userdata.attach(sub_message) return userdata.as_string()
def html(subject:str, body:str, email:str, plain:str=None): message = multipart.MIMEMultipart('alternative') message['Subject'] = '{} | Sportcourts | Спортивные площадки'.format(subject) message['From'] = config.email.login message['To'] = email if plain: message.attach(text.MIMEText(plain, 'plain')) message.attach(text.MIMEText(body, 'html')) return _send_message(email, message)
def make_subpart(content, filename, subtype=None): if subtype is None: subtype = os.path.splitext(filename)[0] if content is None: content = '' msg = (text.MIMEText(content, _subtype=subtype) if subtype else text.MIMEText(content)) msg.add_header('Content-Disposition', 'attachment', filename=filename) return msg
def run(self, context): LOG.info( "Sending email message " "[from=%s, to=%s, reply_to=%s, cc=%s, bcc=%s, subject=%s, " "using smtp=%s, body=%s...]", self.sender, self.to, self.reply_to, self.cc, self.bcc, self.subject, self.smtp_server, self.body[:128] ) if not self.html_body: message = text.MIMEText(self.body, _charset='utf-8') else: message = multipart.MIMEMultipart('alternative') message.attach(text.MIMEText(self.body, 'plain', _charset='utf-8')) message.attach(text.MIMEText(self.html_body, 'html', _charset='utf-8')) message['Subject'] = header.Header(self.subject, 'utf-8') message['From'] = self.sender message['Reply-To'] = header.Header(', '.join(self.reply_to)) message['To'] = ', '.join(self.to) if self.cc: message['cc'] = ', '.join(self.cc) rcpt = self.cc + self.bcc + self.to try: s = smtplib.SMTP(self.smtp_server) if self.password is not None: # Sequence to request TLS connection and log in (RFC-2487). s.ehlo() s.starttls() s.ehlo() s.login(self.sender, self.password) s.sendmail(from_addr=self.sender, to_addrs=rcpt, msg=message.as_string()) except (smtplib.SMTPException, IOError) as e: raise exc.ActionException("Failed to send an email message: %s" % e)
def _create_message(part, subtype, filename): charset = 'us-ascii' try: part.encode(charset) except UnicodeEncodeError: charset = 'utf-8' msg = (text.MIMEText(part, _subtype=subtype, _charset=charset) if subtype else text.MIMEText(part, _charset=charset)) if filename: msg.add_header('Content-Disposition', 'attachment', filename=filename) return msg
def make_subpart(content, filename, subtype=None): if subtype is None: subtype = os.path.splitext(filename)[0] if content is None: content = '' try: content.encode('us-ascii') charset = 'us-ascii' except UnicodeEncodeError: charset = 'utf-8' msg = (text.MIMEText(content, _subtype=subtype, _charset=charset) if subtype else text.MIMEText(content, _charset=charset)) msg.add_header('Content-Disposition', 'attachment', filename=filename) return msg
def applyInterview(): if 'username' not in session.keys(): return signin(None, "/apply_interview/") data = request.form.to_dict() print(data) fromaddr = "*****@*****.**" msg = multipart.MIMEMultipart() msg['From'] = "interview Geek" # msg['To'] = toaddr toaddr = data["email"] msg['Subject'] = "New response to your interview circular" msg_body = "A user named " + session[ "username"] + " from interview Geek responds to your interview circular!!! \n\n Thank You." msg.attach(mailText.MIMEText(msg_body, 'plain')) server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.ehlo() server.login("*****@*****.**", "iplab2019") text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit() return redirect("/circular")
def mp_userdata_from_files(files, compress=False, multipart_mime=None): outer = multipart_mime or multipart.MIMEMultipart() mtypes = [] for i, fp in enumerate(files): mtype = _get_type_from_fp(fp) mtypes.append(mtype) maintype, subtype = mtype.split('/', 1) if maintype == 'text': # Note: we should handle calculating the charset msg = text.MIMEText(fp.read(), _subtype=subtype) fp.close() else: if hasattr(fp, 'name'): fp = open(fp.name, 'rb') msg = base.MIMEBase(maintype, subtype) msg.set_payload(fp.read()) fp.close() # Encode the payload using Base64 encoders.encode_base64(msg) # Set the filename parameter fname = getattr(fp, 'name', "sc_%d" % i) msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(fname)) outer.attach(msg) userdata = outer.as_string() if compress: s = StringIO.StringIO() gfile = gzip.GzipFile(fileobj=s, mode='w') gfile.write(userdata) gfile.close() s.seek(0) userdata = s.read() return userdata
def attach(filename): '''Elkészíti a MIME részt, benne a fájlnévvel''' if not os.path.isfile(filename): return None ctype, encoding = mimetypes.guess_type(filename) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) attachContent = open(filename, 'rb').read() if maintype == 'text': msg = text.MIMEText(attachContent, _subtype=subtype) elif maintype == 'image': msg = image.MIMEImage(attachContent, _subtype=subtype) elif maintype == 'audio': msg = audio.MIMEAudio(attachContent, _subtype=subtype) else: msg = base.MIMEBase(maintype, subtype) msg.set_payload(attachContent) encoders.encode_base64(msg) msg.add_header('Content-Disposition', 'attachment', filename=filename) return msg
def run(self, context): LOG.info( "Sending email message " "[from=%s, to=%s, subject=%s, using smtp=%s, body=%s...]", self.sender, self.to, self.subject, self.smtp_server, self.body[:128]) message = text.MIMEText(self.body, _charset='utf-8') message['Subject'] = header.Header(self.subject, 'utf-8') message['From'] = self.sender message['To'] = ', '.join(self.to) try: s = smtplib.SMTP(self.smtp_server) if self.password is not None: # Sequence to request TLS connection and log in (RFC-2487). s.ehlo() s.starttls() s.ehlo() s.login(self.sender, self.password) s.sendmail(from_addr=self.sender, to_addrs=self.to, msg=message.as_string()) except (smtplib.SMTPException, IOError) as e: raise exc.ActionException("Failed to send an email message: %s" % e)
def send_email(message_body, subject, sender, recipients, server, attachments=[], message_body_type='plain'): msg_root = mimemultipart.MIMEMultipart('mixed') msg_root['Date'] = email.utils.formatdate(localtime=True) msg_root['From'] = sender msg_root['To'] = ', '.join(recipients) msg_root['Subject'] = email.header.Header(subject, 'utf-8') msg_txt = mimetext.MIMEText(message_body, message_body_type, 'utf-8') msg_root.attach(msg_txt) for attachment in attachments: filename = os.path.basename(attachment) with open(attachment, 'rb') as f: msg_attach = mimebase.MIMEBase('application', 'octet-stream') msg_attach.set_payload(f.read()) email.encoders.encode_base64(msg_attach) msg_attach.add_header('Content-Disposition', 'attachment', filename=(email.header.Header( filename, 'utf-8').encode())) msg_root.attach(msg_attach) server.send_message(msg_root)
def run(self): LOG.info("Sending email message " "[from=%s, to=%s, subject=%s, using smtp=%s, body=%s...]" % (self.sender, self.to, self.subject, self.smtp_server, self.body[:128])) # TODO(dzimine): handle utf-8, http://stackoverflow.com/a/14506784 message = text.MIMEText(self.body) message['Subject'] = self.subject message['From'] = self.sender message['To'] = self.to try: s = smtplib.SMTP(self.smtp_server) if self.password is not None: # Sequence to request TLS connection and log in (RFC-2487). s.ehlo() s.starttls() s.ehlo() s.login(self.sender, self.password) s.sendmail(from_addr=self.sender, to_addrs=self.to, msg=message.as_string()) except (smtplib.SMTPException, IOError) as e: raise exc.ActionException("Failed to send an email message: %s" % e)
def _send_smtp(message, subject, to, to_name, sender, sender_name): """SMTP implementation of sending email.""" host = app.config.get('MAIL_HOST') if not host: raise MailFailure('SMTP Server Not Configured') try: server = smtplib.SMTP(host) except (smtplib.SMTPConnectError, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error connecting to SMTP server.') msg = text.MIMEText(message) msg['Subject'] = subject msg['To'] = email.utils.formataddr((to_name, to)) msg['From'] = email.utils.formataddr((sender_name, sender)) try: if app.debug: server.set_debuglevel(True) server.sendmail(sender, [to], msg.as_string()) except (smtplib.SMTPException, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error sending mail to SMTP server.') finally: try: server.quit() except smtplib.SMTPException: pass
def sender_mail(): smt_p = smtplib.SMTP() # 创建对象 smt_p.connect(host='smtp.qq.com', port=25) # 设置smtp服务器 sender = '*****@*****.**' password = "******" # 在qq邮箱设置开启SMTP服务并复制授权码到password smt_p.login(sender, password) # 进行邮箱登录一次,填写你本人的邮箱 receiver_addresses, count_num = [ '*****@*****.**', '*****@*****.**' ], 1 for email_address in receiver_addresses: # 表格中邮箱格式不正确,如有空字符,在发邮件的时候会出现异常报错,捕获到这些异常就跳过 try: msg = multipart.MIMEMultipart() msg['From'] = "zhenguo" # 设置发邮件人 msg['To'] = email_address # 收件人 # msg['Cc'] = '*****@*****.**' msg['subject'] = header.Header('通知', 'utf-8') # 主题名称 msg.attach( text.MIMEText( '您好!\n这是一封测试邮件,使用Python实现自动发邮件,请勿回复本邮件功能~\n\n 祝您工作愉快!', 'plain', 'utf-8')) xlsxpart = application.MIMEApplication( open(r'./data/email_test.xlsx', 'rb').read()) xlsxpart.add_header('Content-Disposition', 'attachment', filename='1.xlsx') msg.attach(xlsxpart) # 添加邮件的附件 smt_p.sendmail(sender, email_address, msg.as_string()) # 发送邮件 time.sleep(10) # sleep10秒避免发送频率过快,可能被判定垃圾邮件。 print('第%d次发送给%s' % (count_num, email_address)) count_num = count_num + 1 except Exception as e: print('第%d次给%s发送邮件异常' % (count_num, email_address)) continue smt_p.quit()
def send(message, subject, to, to_name=None, sender=None, sender_name=None): sender = sender or app.config.get('MAIL_FROM') sender_name = sender_name or app.config.get('MAIL_FROM_NAME') host = app.config.get('MAIL_HOST') try: server = smtplib.SMTP(host) except smtplib.SMTPConnectError as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure() msg = text.MIMEText(message) msg['Subject'] = subject msg['To'] = email.utils.formataddr((to_name, to)) msg['From'] = email.utils.formataddr((sender_name, sender)) try: if app.debug: server.set_debuglevel(True) server.sendmail(sender, [to], msg.as_string()) except smtplib.SMTPException as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure() finally: try: server.quit() except smtplib.SMTPException: pass
def send_email(content: str, subject: str, destination: str) -> bool: """ Send an email. :param str content: the content of the email. :param str subject: the subject of the email. :param str destination: the destination address. :return: true if it sent the email with success. """ if not valid_configuration(): print('Invalid email configuration!') return False # TODO: THIS VERIFICATION SHOULD NOT BE DONE HERE, IT SHOULD BE DONE FOR EVERY POSSIBLE ENTRY OF AN EMAIL if not verify_email(destination): return False msg = emt.MIMEText(content, 'html', 'utf-8') msg['Subject'] = subject msg['From'] = configuration.email_account msg['To'] = destination s = smtplib.SMTP(configuration.email_domain) s.starttls() s.login(configuration.email_user, configuration.email_password) s.sendmail(configuration.email_account, [destination], msg.as_string()) s.quit() return True
def send_text(self, recipient, subject, message_text, email_from=None): """Send an text email. Composes the email into a text.MIMEText object and passes it to the email sending routine. Args: recipient: (str) the email address of the recipient subject: (str) the subject line of the email to be sent text: (str) the body of the email email_from: (str or None) the reported sender of the email. If this is none, the default value from the application configuration is used. """ if email_from is None: email_from = self.app.config['EMAIL_FROM'] message = text.MIMEText(message_text, 'plain', 'utf-8') message['Subject'] = '[{0}] {1}'.format(self.app.config['BALL_NAME'], subject) message['From'] = email_from message['To'] = recipient self.send_message(message)
def execute(self, subscription, messages, **kwargs): subscriber = urllib_parse.urlparse(subscription['subscriber']) params = urllib_parse.parse_qs(subscriber.query) params = dict((k.lower(), v) for k, v in params.items()) conf = kwargs.get('conf') try: for message in messages: p = subprocess.Popen(conf.notification.smtp_command.split(' '), stdin=subprocess.PIPE) # NOTE(Eva-i): Unfortunately this will add 'queue_name' key to # our original messages(dicts) which will be later consumed in # the storage controller. It seems safe though. message['queue_name'] = subscription['source'] msg = text.MIMEText(json.dumps(message)) msg["to"] = subscriber.path msg["from"] = subscription['options'].get('from', '') subject_opt = subscription['options'].get('subject', '') msg["subject"] = params.get('subject', subject_opt) p.communicate(msg.as_string()) except OSError as err: LOG.exception( _LE('Failed to create process for sendmail, ' 'because %s.') % str(err)) except Exception as exc: LOG.exception(_LE('Failed to send email because %s.') % str(exc))
def create_message(self, recipient: str, subject: str, new_entries: list): """ Send an email using the Gmail API with one or more attachments. Args: to: The to recipient of the email. Example: [email protected] subject: The subject of the email. service: An established object with authorised access to the Gmail API for sending emails. message_text: The body of the message to be sent. Raises: N/A Returns: message: A message in the proper format, ready to be sent by the send_email function. """ # Create the message string from LogEntry objects message_text = f"New log entries have been fetched from {self.isp_address}:\n\n" for new_entry in new_entries: message_text.append(new_entry) # Create an email message mime_message = multipart.MIMEMultipart() mime_message["to"] = recipient mime_message["subject"] = subject mime_message.attach(text.MIMEText(message_text, "plain")) # Format message dictionary, ready for sending message = { "raw": base64.urlsafe_b64encode(mime_message.as_bytes()).decode() } return message
def process_impact(git_log, args, config): """Process DocImpact flag. If the 'DocImpact' flag is present for a change that is merged, create a new documentation bug in the openstack-manuals launchpad project based on the git_log. For non-documentation impacts at all states of merge notify the mailing list of impact. """ if args.impact.lower() == 'docimpact': if args.hook == "change-merged": create_bug(git_log, args, config) return email_content = EMAIL_TEMPLATE % (args.impact, args.change_url, git_log) msg = text.MIMEText(email_content) msg['Subject'] = '[%s] %s review request change %s' % \ (args.project, args.impact, args.change) msg['From'] = args.smtp_from msg['To'] = args.dest_address s = smtp_connection(args) s.sendmail(args.smtp_from, args.dest_address, msg.as_string()) s.quit()
def process_message(self, ch, method, properties, body): message_id = body.decode('UTF-8') _LOG.info("Processing message id {}".format(message_id)) try: message = self._get_message_by_id(message_id) email = text.MIMEText(message.text) email['Subject'] = message.subject email['From'] = app.config['FROM_EMAIL'] email['To'] = message.to self._send_email(email) self._update_message_status(message, models.Status.delivered) _LOG.info("Delivered message id {}".format(message_id)) except (exc.NoResultFound, exc.MultipleResultsFound): _LOG.exception("Fatal database exception on message id {}".format( message_id )) except smtplib.SMTPException: if message.retries < app.config['MAX_RETRIES']: _LOG.warning( "Failed to deliver message id {}. Retrying.".format( message_id ), exc_info=True ) self._increment_message_retries(message) self._schedule_retry(message_id) else: _LOG.exception( "Failed to deliver message id {}. Giving up.".format( message_id ) ) self._update_message_status(message, models.Status.error) finally: ch.basic_ack(delivery_tag=method.delivery_tag)
def send_mail(send_from, send_to, subject, text, filename=None): msg = emm.MIMEMultipart() msg['From'] = send_from msg['To'] = send_to msg['Date'] = eu.formatdate(localtime=True) msg['Subject'] = subject msg.attach(emt.MIMEText(text)) # Attach the given file. if filename is not None: with open(filename, "rb") as f: part = ema.MIMEApplication(f.read(), Name=os.path.basename(f)) part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f) msg.attach(part) # Get the recipient MX record. domain = send_to.split('@')[1] server = get_mx_record(domain) smtp = smtplib.SMTP(server) # Send smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def send_mail(config, subject, message, files_to_attach): # unpack some config stuff email = config["email_config"]["email"] password = config["email_config"]["password"] email_name = config["email_config"]["name"] to_list = config["mailing_list"]["emails"] to_list_name = config["mailing_list"]["name"] # connect to gmail server = smtp('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(email, password) # build up the message msg = multipart.MIMEMultipart() msg.attach(text.MIMEText(message)) msg['From'] = email_name msg['To'] = to_list_name msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject for f in files_to_attach: part = base.MIMEBase('application', "octet-stream") with open(f, "rb") as fp: part.set_payload(fp.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(f))) msg.attach(part) server.sendmail(email, to_list, msg.as_string()) server.quit()
def broadcast(self): sender = '*****@*****.**' receivers = ['*****@*****.**', '*****@*****.**'] message = multipart.MIMEMultipart('alternative') message[ 'Subject'] = 'Market Statistics of Last Trading Day ({})'.format( self.__last_date) main_text = """ Volume weighted average spread: ${:<10.4f} SPY 5-tick momentum index: {:<10.4f} """.format(self.vol_avg_spread(), self.spy_accuracy(self.__spy_df.price, 0.05)) message.attach(text.MIMEText(main_text, 'plain')) try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message.as_string()) smtpObj.quit() print("Successfully sent email") except smtplib.SMTPException: print("Error: cannot send email")
def __send_email__(info): sender = app.config.get('EMAIL')['user'] recipients = info.get('recipients') subject = info.get('subject') text = info.get('text') message = """From: <{0}> To: {1} Subject: {2} {3}""".format(sender, ",".join(["<{0}>".format(r) for r in recipients]), subject, text) message = email_text.MIMEText(message, _charset="UTF-8") #try: server = smtplib.SMTP( app.config.get('EMAIL')['host'], app.config.get('EMAIL')['port']) server.ehlo() if app.config.get('EMAIL')['tls']: server.starttls() server.ehlo() server.login(sender, app.config.get("EMAIL")["password"]) server.sendmail(sender, recipients, message.as_string()) server.close() #except: # print("Error trying to send email") # return False return True
def return_attachment(gmail, item_dict): ''' Creates an attachment and then sends it to the string gmail, from the dictionary item_dict. Uses the smtp library. ''' file = open("return_attachment.txt", "w") for key, value in item_dict.items(): file.write(str(key) + " " + str(value) + "\n") file.close() del (file) #for some reason, you have to remove the variable and redo it. mjsg = multipart.MIMEMultipart() #create email base. mjsg['From'] = "*****@*****.**" mjsg['To'] = gmail mjsg['Subject'] = "Smart_list" attn = open("return_attachment.txt", "r") #create attachments. attachment = text.MIMEText(attn.read()) attachment.add_header('Content-Disposition', 'attachment', filename=attn.name) mjsg.attach(attachment) #attach attachment... I love documentation. try: context = ssl.create_default_context() #send email and exit smtp = smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) smtp.login("*****@*****.**", "MatterH27h") smtp.sendmail("*****@*****.**", gmail, mjsg.as_string()) smtp.close() except: print( "Some sort of network failure happened trying to send the eamil." ) #If you get this it means you have problems with either the network or the 'gmail' (email) input.