def send(self): msg = MIMEMultipart() msg["Subject"] = time.strftime('%Y-%m-%d-%H-%M') + self.tile msg["To"] = ','.join(self.email_to) msg["From"] = self.email_from # 邮件正文部分 part = MIMEText(self.text) msg.attach(part) # 邮件附件_html报告 part = MIMEApplication(open(self.file, 'rb').read()) if sys.platform == 'win32': part.add_header('Content-Disposition', 'attachment', filename=self.file.split('\\')[-1]) else: part.add_header('Content-Disposition', 'attachment', filename=self.file.split('/')[-1]) msg.attach(part) # 邮件附件_html报告样式CSS if sys.platform == 'win32': old = self.file.split('\\')[-1] else: old = self.file.split('/')[-1] new_style_path = self.file.replace(old, self.style_path) part = MIMEApplication(open(new_style_path, 'rb').read()) part.add_header('Content-Disposition', 'attachment', filename='style.css') msg.attach(part) # 发送邮件 host = 'smtphz.qiye.163.com' if self.type == '163' else 'smtp.qq.com' if host.__contains__('163'): try: server = smtplib.SMTP_SSL(host, 994, timeout=10) server.login(self.email_from, self.pwd) server.sendmail(self.email_from, self.email_to, msg.as_bytes()) server.close() except Exception as e: print('连接失败', e) else: try: server = smtplib.SMTP_SSL(host, 465, timeout=10) server.login(self.email_from, self.pwd) server.sendmail(self.email_from, self.email_to, msg.as_bytes()) server.close() except Exception as e: print('连接失败', e)
def send_message_to_techsub(service, user_id, email_of_student, name_of_student, validation_dictionary, error_dictionary, number_of_templates): """ Рассылка писем ТП. Вызывается преподавателю, если у студента есть ошибки в работе или ТП, если упал один из модулей :param service: авторизация через мыло :param user_id: наше мыло или спец слово 'me' :param email_of_student: мыло студента :param name_of_student: имя и фамилия студента :param validation_dictionary: словарь с валидации письма, в котором есть ('Numder')номер работы и ('URL')ссылка на работу :param error_dictionary: словарь с ошибками в коде студента :param number_of_templates: номер используемого для заполнения письма шаблона """ if number_of_templates == 0: str_of_er = error_in_work(error_dictionary) else: str_of_er = "" message_templates = funcTs(name_of_student, validation_dictionary, str_of_er) sending_msg = {} sending_msg['From'] = GMAIL_OF_TRPO sending_msg = MIMEMultipart('alternative') sending_msg = MIMEText(message_templates[number_of_templates]['hello'] + message_templates[number_of_templates]['our_msg'] + SIGNATURE) sending_msg['Subject'] = message_templates[number_of_templates]['title'] # Косяк!!! if number_of_templates == 0: for i in MAS_OF_TO: sending_msg['To'] = i raw = base64.urlsafe_b64encode(sending_msg.as_bytes()) raw = raw.decode() body = {'raw': raw} else: sending_msg['To'] = EMAIL_OF_TEACHER raw = base64.urlsafe_b64encode(sending_msg.as_bytes()) raw = raw.decode() body = {'raw': raw} send_msg = service.users().messages().send(userId=user_id, body=body).execute()
def create_message_with_attachment(sender, to, subject, message_text, message_html, file): """Create a message for an email. Args: sender: Email address of the sender. to: Email address of the receiver. subject: The subject of the email message. message_text: The text of the email message. file: The path to the file to be attached. Returns: An object containing a base64url encoded email object. """ message = MIMEMultipart() message['to'] = to message['from'] = sender message['subject'] = subject # message.attach(MIMEText(message_text, 'plain')) message.attach(MIMEText(message_html, 'html')) message = addAttachments(file, message) raw = base64.urlsafe_b64encode(message.as_bytes()) raw = raw.decode() body = {'raw': raw} return body
def send_mail_message(subject, content): this_dir = Path(__file__).parent store = file.Storage("credentials.json") credentials = store.get() if not credentials or credentials.invalid: client_secret_json = json.loads((this_dir / "client_secret.json").read_text()) client_secret_json["installed"]["client_secret"] = os.environ["TOX_DEV_GOOGLE_SECRET"] with tempfile.NamedTemporaryFile(mode="w+t") as temp_filename: json.dump(client_secret_json, temp_filename) temp_filename.flush() flow = client.flow_from_clientsecrets( filename=temp_filename.name, scope="https://www.googleapis.com/auth/gmail.send", ) credentials = tools.run_flow(flow, store) service = discovery.build("gmail", "v1", http=credentials.authorize(httplib2.Http())) message = MIMEMultipart("alternative") message["Subject"] = subject message["From"] = "*****@*****.**" recipients = ["*****@*****.**", "*****@*****.**"] message["To"] = ", ".join(recipients) message.attach(MIMEText(content, "plain")) raw_message_no_attachment = base64.urlsafe_b64encode(message.as_bytes()) raw_message_no_attachment = raw_message_no_attachment.decode() body = {"raw": raw_message_no_attachment} message_sent = service.users().messages().send(userId="me", body=body).execute() message_id = message_sent["id"] print(f"\tMessage sent with id: {message_id}")
def create_message( self, to: str, subject: str, message_text: str, attachments: list = None, ): """Create a message for an email. :param to: message recipient :param subject: message subject :param message_text: message body text :param attachment: list of files to add as message attachments :return: An object containing a base64url encoded email object """ mimeMessage = MIMEMultipart() mimeMessage["to"] = to mimeMessage["subject"] = subject mimeMessage.attach(MIMEText(message_text, "plain")) for at in attachments: self.add_attachment_to_message(mimeMessage, at) return { "raw": base64.urlsafe_b64encode(mimeMessage.as_bytes()).decode() }
def sendMail(send_to, send_from, subject, text, attachments, priority=Priority.NORMAL): if attachments: mail = MIMEMultipart() part = MIMEText(text.encode('utf-8'), 'plain', 'utf-8') mail.attach(part) for attachment in attachments: if attachment.mimetype == 'text/html': part = MIMEText(attachment.data.encode('utf-8'), 'html', 'utf-8') elif attachment.mimetype == 'application/pdf': part = MIMEApplication(attachment.data, 'pdf', Name=attachment.name) else: part = MIMEApplication(attachment.data, Name=attachment.name) part['Content-Disposition'] = 'attachment; filename="{}"'.format(attachment.name) mail.attach(part) else: mail = MIMEText(text.encode('utf-8'), 'plain', 'utf-8') mail['Subject'] = Header(subject, 'utf-8') mail['To'] = COMMASPACE.join(send_to) mail['From'] = send_from mail['Date'] = formatdate(localtime=True) if priority is not Priority.NORMAL: mail['X-Priority'] = str(int(priority)) process = subprocess.Popen( ["/usr/sbin/sendmail", "-oi", "-t"], stdin=subprocess.PIPE, ) process.communicate(mail.as_bytes())
def create_message(to, subject, message_text): message = MIMEMultipart() message.attach(MIMEText(message_text, 'plain')) message['to'] = to message['subject'] = subject return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}
def compose(self, sender, to, subject, body, files=None): """ Compose a message. :param sender: Sender email/name :type sender: str :param to: Recipient email or comma-separated list of recipient emails :type to: str :param subject: Email subject :type subject: str :param body: Email body :type body: str :param files: Optional list of files to attach :type files: list """ message = MIMEMultipart() if files else MIMEText(body) message['to'] = to message['from'] = sender message['subject'] = subject if files: for file in files: msg = MIMEText(body) message.attach(msg) content_type, encoding = mimetypes.guess_type(file) if content_type is None or encoding is not None: content_type = 'application/octet-stream' main_type, sub_type = content_type.split('/', 1) with open(file, 'rb') as fp: content = fp.read() if main_type == 'text': msg = mimetypes.MIMEText(content, _subtype=sub_type) elif main_type == 'image': msg = MIMEImage(content, _subtype=sub_type) elif main_type == 'audio': msg = MIMEAudio(content, _subtype=sub_type) elif main_type == 'application': msg = MIMEApplication(content, _subtype=sub_type, _encoder=encode_base64) else: msg = MIMEBase(main_type, sub_type) msg.set_payload(content) filename = os.path.basename(file) msg.add_header('Content-Disposition', 'attachment', filename=filename) message.attach(msg) service = self.get_service('gmail', 'v1') body = { 'raw': base64.urlsafe_b64encode(message.as_bytes()).decode() } message = (service.users().messages().send( userId='me', body=body).execute()) return message
def MIME_mail_build(src_name, src_mail, dest_name, dest_mail, title, mail_body): # Override python's weird assumption that utf-8 text should be encoded with # base64, and instead use quoted-printable (for both subject and body). I # can't figure out a way to specify QP (quoted-printable) instead of base64 in # a way that doesn't modify global state. :-( if sys.version_info[0] == 2: Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') # pylint: disable=undefined-variable, no-member # This example is of an email with text and html alternatives. multipart = MIMEMultipart('alternative') # We need to use Header objects here instead of just assigning the strings in # order to get our headers properly encoded (with QP). # You may want to avoid this if your headers are already ASCII, just so people # can read the raw message without getting a headache. multipart['Subject'] = Header(title.encode('utf-8'), 'UTF-8').encode() multipart['Date'] = utils.formatdate() multipart['To'] = Header(dest_name.encode('utf-8'), 'UTF-8').encode() + " <" + dest_mail + ">" multipart['From'] = Header(src_name.encode('utf-8'), 'UTF-8').encode() + " <" + src_mail + ">" multipart['X-Mailer'] = "fnord" multipart.attach(MIMEText(mail_body.encode('utf-8'), 'plain', 'UTF-8')) if sys.version_info[0] == 2: return StringIO(multipart.as_string()) else: return BytesIO(multipart.as_bytes()) # pylint: disable=no-member
def create_mail(sender: str, to: str, subject: str, msg_html: str, msg_plain: str) -> dict: """Create an email message. I got this to work thanks to https://stackoverflow.com/questions/37201250/sending-email-via-gmail-python Args: sender (str): Mail address of sender to (str): Destination mail address subject (str): Mail subject msg_html (str): Html content for the mail msg_plain (str): String version of the mail Returns: Message body in mime format """ logger.info('creating mail') msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = sender msg['To'] = to msg.attach(MIMEText(msg_plain, 'plain')) msg.attach(MIMEText(msg_html, 'html')) raw = base64.urlsafe_b64encode(msg.as_bytes()) raw = raw.decode() body = {'raw': raw} return body
def send_mail(mail_to, body, file): if "MAIL_ADDRESS" not in os.environ or "SERVICE_ACCOUNT_STR" not in os.environ: raise MailConfigurationException("Mail isn't configured properly") mail_from = os.environ["MAIL_ADDRESS"] service_account_str = os.environ["SERVICE_ACCOUNT_STR"] msg = MIMEMultipart() msg["From"] = mail_from msg["To"] = COMMASPACE.join(mail_to) msg["Date"] = formatdate(localtime=True) create_mail(msg, body) filename = "kvitteringsskjema.pdf" part = MIMEApplication(file, Name=filename) part["Content-Disposition"] = f'attachment; filename="{filename}"' msg.attach(part) logging.info(f'Sending mail to {", ".join(mail_to)}') service = service_account_login(mail_from, service_account_str) raw = base64.urlsafe_b64encode(msg.as_bytes()) body = {'raw': raw.decode()} messages = service.users().messages() messages.send(userId="me", body=body).execute()
def build_message(filename=None, path=None, update=False): """ Builds a MIME message with a csv attachment. """ msg = MIMEMultipart() subject = 'Brandish {} VS Worker - Invalid Items'.format(ENVIRONMENT) if update: subject = 'Brandish {} VS Worker - Invalid Updated Items'.format(ENVIRONMENT) msg['Subject'] = subject msg['From'] = SUPPORT_EMAIL msg['To'] = ', '.join(EMAILS) text = """ Please find attached a spreadsheet of items that could not be updated from YouTube. Common reasons for an item not being updated: - Video has gone private or deleted - Video is from Vimeo (We're working on that) """ msg.preamble = text msg.attach(MIMEText(text, 'plain')) if filename and path: # pragma: no cover try: with open(path, 'r') as fp: attachment = MIMEText(fp.read(), _subtype='csv') attachment.add_header("Content-Disposition", "attachment", filename=filename) msg.attach(attachment) except FileNotFoundError: # pragma: no cover logger.exception("Error attaching file.") return msg.as_bytes()
def export_to_flat_file(self): msg = EmailMessage() # timestamp if self.timestamp: timestamp = self.timestamp.isoformat(timespec='microseconds') else: timestamp = None msg['timestamp'] = timestamp # hash_chain if self.hash_chain__object: hash_chain = self.hash_chain__object.base16().decode('ascii') else: hash_chain = None msg['hash_chain'] = hash_chain # json payload and attachments mult = MIMEMultipart() mult.attach(msg) # payload payload = json.dumps(self.payload, indent=4) mult.attach( MIMEApplication(payload, _encoder=encode_7or8bit, description='payload')) # attachments for attachment in self.attachments: mult.attach( MIMEApplication(attachment, _encoder=encode_7or8bit, description='attachment')) # # return as bytes return mult.as_bytes()
def create_message(sender, to_, cc_, bcc_, subject_, message_text, filenames_): try: global get_msg_attach, MIMEMultipart, MIMEText, base64 message = MIMEMultipart() message.attach(MIMEText(message_text, 'html')) message['to'] = to_ message['cc'] = cc_ message['bcc'] = bcc_ message['from'] = sender message['subject'] = subject_ for file in filenames_: filename_ = os.path.basename(file) msg_ = get_msg_attach(file) msg_.add_header('Content-Disposition', 'attachment', filename=os.path.basename(filename_)) message.attach(msg_) raw_message = base64.urlsafe_b64encode(message.as_bytes()) return {'raw': raw_message.decode("utf-8")} except Exception as e: print("Esta fue el error:", e) print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
def MIME_mail_build(src_name, src_mail, dest_name, dest_mail, title, mail_body): # Override python's weird assumption that utf-8 text should be encoded with # base64, and instead use quoted-printable (for both subject and body). I # can't figure out a way to specify QP (quoted-printable) instead of base64 in # a way that doesn't modify global state. :-( if six.PY2: from email import Charset # pylint: disable=no-name-in-module Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') # pylint: disable=undefined-variable, no-member # This example is of an email with text and html alternatives. multipart = MIMEMultipart('alternative') # We need to use Header objects here instead of just assigning the strings in # order to get our headers properly encoded (with QP). # You may want to avoid this if your headers are already ASCII, just so people # can read the raw message without getting a headache. multipart['Subject'] = Header(title.encode('utf-8'), 'UTF-8').encode() multipart['Date'] = utils.formatdate() multipart['To'] = Header(dest_name.encode('utf-8'), 'UTF-8').encode() + " <" + dest_mail + ">" multipart['From'] = Header(src_name.encode('utf-8'), 'UTF-8').encode() + " <" + src_mail + ">" multipart['X-Mailer'] = "fnord" multipart.attach(MIMEText(mail_body.encode('utf-8'), 'plain', 'UTF-8')) if six.PY2: multipart_as_bytes = six.binary_type(multipart.as_string()) else: multipart_as_bytes = multipart.as_bytes() # pylint: disable=no-member return BytesIO(multipart_as_bytes) # pylint: disable=no-member
def generate_email(allimages): msg =MIMEMultipart('alternative') msg['Date'] = email.header.Header( email.utils.formatdate() ) msg['Subject'] = subject msg['From'] = ( '\"' + modelname + '\" ' + '<' + emailll + '>') msg['To'] = leadmail msg.add_header("Message-ID", email.utils.make_msgid(domain=dname)) # headers=[ b'Date', b'Subject',b'From', b'To', b'Message-ID'] # if leadmail_mid != '': msg.add_header('In-Reply-To', '<' + leadmail_mid + '>' ) msg.add_header('References', '<' + leadmail_mid + '>' ) msg.attach(MIMEText(textbody, 'plain')) msg.attach(MIMEText(body, 'html', 'utf-8')) for image in allimages: msg.attach(attach_image(image)) try: headers=[b'Subject',b'From', b'Date', b'To', b'Message-ID',b'In-Reply-To',b'References'] keypath = "/home/metoa/mysite/static/"+str(auser)+"/" privateKey = open(os.path.join(keypath, dselctor+'.'+dname+'.pem')).read() sig = dkim.sign(msg.as_bytes(), bytes(dselctor,encoding='utf8'), bytes(dname,encoding='utf8'), privateKey.encode(), include_headers=headers) sig = sig.decode() # Add the DKIM-Signature msg['DKIM-Signature'] = sig[len("DKIM-Signature: "):] except Exception as e: print(e, flush = True) pass return msg
def format_mail(from_, to, subject, date, pure_text_prefix, content): content_lines = content.splitlines() try: text_content = pure_text_prefix + u"\n\n" + html2text.html2text(content) except: text_content = "No able to convert to text, sorry. Read the html version instead" html_content = pure_text_prefix + u"\n\n" + content text_content = text_content.encode("utf-8") html_content = html_content.encode("utf-8") msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = from_ msg['To'] = to if date: if isinstance(date, six.string_types): msg['Date'] = date else: msg["Date"] = email.utils.formatdate((int(date.strftime("%s"))), date) plain_part = MIMEText(text_content, _subtype='plain', _charset="utf-8") html_part = MIMEText(html_content, _subtype='html', _charset="utf-8") msg.attach(plain_part) msg.attach(html_part) if six.PY3: msg_bytes = msg.as_bytes() else: msg_bytes = msg.as_string() msg["Message-Id"] = "<{}>".format(md5(msg_bytes).hexdigest()) return msg
def run(self, dispatcher, tracker, domain): print("In ActionSendEmail class :") from_user = '******' to_user = tracker.get_slot('emailid') if to_user is None: dispatcher.utter_message(template="utter_ask_email_id") return [] dispatcher.utter_message("Sending email to {}".format(to_user)) password = '******' server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(from_user, password) subject = 'Restaurant Results' msg = MIMEMultipart() msg['From'] = from_user msg['TO'] = to_user msg['Subject'] = subject f = open('restaurants.txt') restaurants = json.loads(str(f.read())) from jinja2 import Template t = Template(open('data/mail_body.html').read()) body = t.render(restaurants=restaurants, int=int) with open('test_email', 'w') as f: f.write(body) msg.attach(MIMEText(body, 'html', 'utf-8')) text = msg.as_bytes() server.sendmail(from_user, to_user, text) print('Email sent successfully !!!') server.close() dispatcher.utter_message("Email sent successfully!!!") return []
def create_message(sender, to, subject, message_text, attachments): message = MIMEMultipart() message['to'] = to message['from'] = sender message['subject'] = subject msg = MIMEText(message_text) message.attach(msg) for path in attachments: content_type, encoding = mimetypes.guess_type(path) if content_type is None or encoding is not None: content_type = 'application/octet-stream' main_type, sub_type = content_type.split('/', 1) with open(path, 'rb') as fp: if main_type == 'text': msg = MIMEText(fp.read(), _subtype=sub_type) elif main_type == 'image': msg = MIMEImage(fp.read(), _subtype=sub_type) elif main_type == 'audio': msg = MIMEAudio(fp.read(), _subtype=sub_type) else: msg = MIMEBase(main_type, sub_type) msg.set_payload(fp.read()) filename = os.path.basename(path) msg.add_header('Content-Disposition', 'attachment', filename=filename) message.attach(msg) return { 'raw': base64.urlsafe_b64encode(message.as_bytes()).decode('ascii') }
def mail_send(args, content): """ Send the mail via sendmail (postfix) command Arguments: args {Namespace} -- Namespace containing all arguments. content {string} -- HTML content as string. """ infomsg("Start sending the individual mails", "Mail") for receiver in args.receivers: message = MIMEMultipart('alternative') message['From'] = "{} <{}>".format(args.name, args.address) message['To'] = receiver if args.date: td = datetime.today() current_day = datetime.strftime( datetime(td.year, td.month, td.day), "%d %B %Y") message['Subject'] = '{subject} since {date}'.format( subject=args.subject, date=current_day) else: message['Subject'] = '{subject}'.format(subject=args.subject) message.attach(MIMEText(content, 'html')) p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE) stderr = p.communicate(message.as_bytes())[1] if p.returncode != 0: infomsg("sendmail returned with non-zero return value", "Mail", stderr) infomsg("Send mail", "Mail", (receiver, ))
def create_message(sender, to, subject, csv): #message = MIMEMultipart() message = MIMEMultipart() message['from'] = sender message['to'] = to message['subject'] = subject # Send the time it was updated as the body of the e-mail dt_object = datetime.utcnow() - timedelta(hours=7) msg = MIMEText('Hi! Your file was updated.' \ '\nTime of update: ' + dt_object.strftime('%m/%d/%Y, %I:%M:%S %p') \ + ' (Los Angeles Time)') message.attach(msg) # Attach the .csv file record = MIMEBase('application', 'octet-stream') # print(csv) record.set_payload(csv) encoders.encode_base64(record) record.add_header('Content-Disposition', 'attachment', filename='medicare.csv') message.attach(record) # Return the message raw = base64.urlsafe_b64encode(message.as_bytes()) raw = raw.decode() return {'raw': raw}
def mail(text, STATUS, filename=None): """ STATUS: INFO, ERROR text: Message to be sent """ # For each contact, send the email: msg = MIMEMultipart() # create a message # add in the actual person name to the message template # Prints out the message body for our sake # setup the parameters of the message msg['From'] = MY_ADDRESS recipients = ["*****@*****.**"] msg['To'] = ', '.join(recipients) msg['Subject'] = "{}-{}-{}".format(BOTNAME, SERVERNAME, STATUS) msg.attach(MIMEText(text, 'plain')) if filename: 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", "attachment; filename= {}".format(filename)) msg.attach(part) message = {'raw': base64.urlsafe_b64encode(msg.as_bytes()).decode()} try: message = gmail_service.users().messages().send( userId='me', body=message).execute() print('Message Id: %s' % message['id']) return message except Exception as error: print('A mail error occurred: %s' % error)
def create_message_with_attachment(self, sender, to, subject, message_text, file): message = MIMEMultipart() message['to'] = to message['from'] = sender message['subject'] = subject msg = MIMEText(message_text) message.attach(msg) content_type, encoding = mimetypes.guess_type(file) if content_type is None or encoding is not None: content_type = 'application/octet-stream' main_type, sub_type = content_type.split('/', 1) if main_type == 'text': fp = open(file, 'rb') msg = MIMEText(fp.read(), _subtype=sub_type) fp.close() elif main_type == 'image': fp = open(file, 'rb') msg = MIMEImage(fp.read(), _subtype=sub_type) fp.close() else: fp = open(file, 'rb') msg = MIMEBase(main_type, sub_type) msg.set_payload(fp.read()) fp.close() filename = os.path.basename(file) msg.add_header('Content-Disposition', 'attachment', filename=filename) message.attach(msg) return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}
def send_website_msg_to_business(mailer, website_json): # Configure the emailer, first setting sender and receiver to business sender = os.environ["EMAIL_SENDER"] receiver = os.environ["EMAIL_RECEIVER"] client_email = website_json["email"] # Create message from form message to send to business text = f'{website_json["message"]}\n\n\ {website_json["name"]}\n\ {website_json["address"] if ("address" in website_json and website_json["address"] is not None) else "No physical address provided."}\n\ {website_json["email"]}\n\ Preffered Contact Method: {website_json["pref_contact"]}' message = MIMEMultipart() message["Subject"] = "Message from MFP Website" message["From"] = f"MFP Website<{sender}>" message["Reply-To"] = client_email message["To"] = receiver message.attach(MIMEText(text, 'plain')) raw_string = base64.urlsafe_b64encode(message.as_bytes()).decode() try: mailer.users().messages().send(userId='me', body={ 'raw': raw_string }).execute() return 200 except Exception as e: raise RuntimeError( "Failed to send email to client. Email address likely at fault.")
def file_request(self): send_labels = [ label_id for _label, label_id in auth.get_label_ids(GMAIL_SERVICE).items() if _label in ["FOIA", "FOIA - UNFINISHED"] ] # https://stackoverflow.com/questions/35873847/mime-multipart-being-sent-as-noname-on-python-3 message = MIMEMultipart("alternative") message["to"] = self["foia_email"] message["from"] = FROM_EMAIL message[ "subject"] = f"{self['public_records_act']} Request: {self._parse_field('subject_line')}" if "cc" in self.params: message["cc"] = self.params["cc"] if "bcc" in self.params: message["bcc"] = self.params["bcc"] html_content, text_content = self.compose_request() mime_text = MIMEText(text_content, "text") mime_html = MIMEText(html_content, "html") message.attach(mime_text) message.attach(mime_html) # This part of the solution from https://stackoverflow.com/questions/42601324/python-3-6-gmail-api-send-email-with-attachement final_message = { "raw": base64.urlsafe_b64encode(message.as_bytes()).decode() } sent_message = (GMAIL_SERVICE.users().messages().send( userId="me", body=final_message).execute()) sent_message = (GMAIL_SERVICE.users().messages().modify( userId="me", id=sent_message["id"], body={ "addLabelIds": send_labels }).execute()) return sent_message
def sendmail(new_run, alerts_by_run, mail): text = "%s\n" % str(new_run) for (_, alerts) in alerts_by_run.items(): text += "\nProbably a copy of\n%s\nSimilarities:\n" % (str( alerts[0].original_run)) text += "\n".join( map( lambda x: "%s\t%s" % (x.checker, format_similarity(x.similarity)), alerts)) text += '\n' top_alert = next(iter(alerts_by_run.values()))[0] for (_, alerts) in alerts_by_run.items(): for alert in alerts: if not (alert.similarity is None) and ( (top_alert.similarity is None) or (alert.similarity > top_alert.similarity)): top_alert = alert message = MIMEMultipart() message["To"] = mail message["Subject"] = "[%d] Suspicious run: %d, %s, %s, %s. %s: %s" % ( new_run.contest_id, new_run.id, new_run.problem, new_run.lang, new_run.user_login, top_alert.checker, format_similarity(top_alert.similarity)) message.attach(MIMEText(text)) message.attach(create_attachment("suspisious_run", new_run)) for (old_run_id, alerts) in alerts_by_run.items(): message.attach( create_attachment("original_%d" % old_run_id, alerts[0].original_run)) p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE) p.communicate(message.as_bytes())
def create_message_html(self, sender, to, subject, message_text, message_html): """Create an html message for an email. `Args:` sender: str Email address of the sender. to: str Email address(es) of the recipient(s). subject: str The subject of the email message. message_text: str The text of the email message. message_html: str The html formatted text of the email message. `Returns:` dict An object containing a base64url encoded email object. """ logger.info("Creating an html message...") message = MIMEMultipart('alternative') message['subject'] = subject message['from'] = sender message['to'] = to if message_text: message.attach(MIMEText(message_text, 'plain')) message.attach(MIMEText(message_html, 'html')) msg = {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()} logger.debug(msg) logger.info("Encoded html message sucessfully created.") return msg
def send_email(data): # Create Email sender = "*****@*****.**" revicever = "*****@*****.**" subject = "[METPY] Cork Weather" body = str(data) msg = MIMEMultipart() msg['Subject'] = subject msg['To'] = revicever msg.attach(MIMEText(body, 'plain')) # Attach Image image = open(MET_GRAPH_FILE, 'rb').read() msg.attach(MIMEImage(image, name=MET_GRAPH_FILE)) raw = base64.urlsafe_b64encode(msg.as_bytes()) raw = raw.decode() email_msg = {'raw': raw} # Auth Gmail creds = auth_gmail() if (creds == ''): print(RED + "Failed to Get Gmail Creds" + ENDC) return False # Send Email service = build('gmail', 'v1', credentials=creds) results = service.users().messages().send(userId='me', body=email_msg).execute() print(results) return results
def send_mail(mail_user: str, mail_pwd: str, receiver: str, message: MIMEMultipart): logger = logging.getLogger(__name__) try: if mail_user.endswith("gmail.com"): server = smtplib.SMTP_SSL("smtp.gmail.com", 465) elif mail_user.endswith("yahoo.com"): server = smtplib.SMTP_SSL("smtp.mail.yahoo.com", 465) elif mail_user.endswith("mg.watxaut.com"): server = smtplib.SMTP_SSL("smtp.eu.mailgun.org", 465) else: return False server.ehlo() server.login(mail_user, mail_pwd) server.sendmail(mail_user, receiver, message.as_bytes()) server.close() logger.info('Email sent to : "{}"!'.format(receiver)) return True except smtplib.SMTPException: logger.error("Something went wrong sending the mail: '{}'".format( traceback.format_exc())) return False
def create_message(sender, to_list, subject, body, cc_list=None, bcc_list=None, attach_paths=None): """Create an email message for the Google Gmail API. Arguments: message: a MIMEText or MIMEMultipart object. Returns: An object containing a base64url encoded email object. """ message = MIMEText(body) mime = MIMEMultipart() if attach_paths else message _add_email_info(mime, sender, to_list, subject, cc_list=cc_list, bcc_list=bcc_list) if attach_paths: mime.attach(message) printable = mime.as_string() if attach_paths: for path in attach_paths: _add_attachment(mime, path) printable += "\n**Attachment paths:\n\n" for i, path in enumerate(attach_paths, start=1): printable += "{0}. {1}\n".format(i, os.path.abspath(path)) raw = base64.urlsafe_b64encode(mime.as_bytes()) raw = raw.decode() return {'raw': raw}, printable
def send_mail(to, subject, message): log.debug("Inside send_mail function.") try: sender = str(config.email['id']) credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = sender msg['To'] = to msg.attach(MIMEText(message, 'html')) raw = base64.urlsafe_b64encode(msg.as_bytes()) raw = raw.decode() raw = {'raw': raw} user_id = "me" message = (service.users().messages().send(userId=user_id, body=raw).execute()) log.debug('Message Id: %s' % message['id']) return message except errors.HttpError as error: log.error('Error in send_mail. An error occurred: %s' % error) return None
def create_message_with_attachment(self, form, file): email_send = form['recipient_email'] subject = form['subject'] body = 'Sent via ' + 'ScanUpload' + '\n' + now.strftime( "%Y-%m-%d %H:%M") + '\n' + form['body'] message = MIMEMultipart() message['to'] = ", ".join(email_send) message['subject'] = subject msg = MIMEText(body) message.attach(msg) content_type, encoding = mimetypes.guess_type("file.pdf") main_type, sub_type = content_type.split('/', 1) if content_type is None or encoding is not None: content_type = 'application/octet-stream' else: msg = MIMEBase(main_type, sub_type) msg.set_payload(file, 'utf-8') msg.add_header('Content-Disposition', 'attachment', filename='Document') message.attach(msg) return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}
def send_captcha(self, captcha): def get_format_addr(data): name, addr = parseaddr(data) return formataddr((Header(name, "utf-8").encode(), addr)) msg = MIMEMultipart() message = MIMEText(captcha, "plain", "utf-8") msg["From"] = get_format_addr("Junkui Zhang <%s>" % self.user) msg["To"] = get_format_addr("Me <%s>" % self.user) msg["Subject"] = Header("<!CAPTCHA!>", "utf-8").encode() msg.attach(message) with open("0.jpg", "rb") as file: pic = MIMEBase("image", "jpg", filename="0.jpg") pic.add_header("Content-Disposition", "attachment", filename="0.jpg") pic.add_header("Content-ID", "<0>") pic.add_header("X-Attachment-ID", "0") pic.set_payload(file.read()) encode_base64(pic) msg.attach(pic) server = smtplib.SMTP(self.smtp_server, 25) server.login(self.user, self.pwd) server.sendmail(self.user, [self.user], msg.as_bytes()) server.quit()
def CreateMessageWithAttachment(self, sender, to, subject, message_text, file_dir, filename): message = MIMEMultipart() message['to'] = to message['from'] = sender message['subject'] = subject msg = MIMEText(message_text) message.attach(msg) file_dir = file_dir filename = filename with open(os.path.join(file_dir, filename), "rb") as attachment: # The content type "application/octet-stream" means that a MIME attachment is a binary file part = MIMEBase("application", "octet-stream") part.set_payload(attachment.read()) # Encode to base64 encoders.encode_base64(part) # Add header part.add_header("Content-Disposition", "attachment; filename={f}".format(f=filename)) # Add attachment to your message and convert it to string message.attach(part) return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}
def formatEmail(self): msg = MIMEMultipart('alternative') msg['To'] = self.to msg['Subject'] = self.subject msg.attach(MIMEText(self.plain, 'plain')) msg.attach( MIMEText(self.html, 'html') ) return {'raw': urlEncode(msg.as_bytes()).decode()}
def send_email(email_address): """Sends email to the 'email_address' parameter. This email will have the two books attached to it.""" print(email_address, 'wants the books!') logging.basicConfig(filename='Bot.log', format='%(name)s : %(levelname)s : %(message)s', level=logging.INFO) logging.info('\n\n\n\n\n{} : {}'.format(datetime.today().replace(microsecond=0), email_address)) CLIENT_SECRET_FILE = "credentials.json" API_NAME = 'gmail' API_VERSION = 'v1' SCOPES = ['https://mail.google.com/'] service = create_service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES) emailMsg = (make_message()) mimeMessage = MIMEMultipart() mimeMessage['to'] = email_address mimeMessage['subject'] = 'Books' mimeMessage.attach(MIMEText(emailMsg, 'plain')) raw_string = base64.urlsafe_b64encode(mimeMessage.as_bytes()).decode() message = service.users().messages().send( userId='me', body={'raw': raw_string}).execute() print(message) print(email_address, 'has received the books.')
def CreateMessage(sender, to, subject, msgHtml, msgPlain): msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = sender msg['To'] = to msg.attach(MIMEText(msgPlain, 'plain')) msg.attach(MIMEText(msgHtml, 'html')) raw = base64.urlsafe_b64encode(msg.as_bytes()) raw = raw.decode() body = {'raw': raw} return body
def form_message(self): """ Form an RFC822 message, with an appropriate MIME attachment """ msg = MIMEMultipart() for header in ("To", "Cc", "Bcc", "Subject", "References", "In-Reply-To"): if header.lower() in self.mail_dict: msg[header] = self.mail_dict[header.lower()][0] try: fname = os.path.split(self.mail_dict["attach"][0])[1] if "subject" not in self.mail_dict: msg["Subject"] = _("Sending %s") % fname except KeyError: pass """ prepare preamble to be ascii encoded: bug #29 """ """ normalization """ preamble = unicodedata.normalize('NFKD', u"%s" % str(_("Mime message attached"))) """ stripping of what is still ascii incompatible """ preamble = preamble.encode('ascii', 'ignore').decode('ascii') msg.preamble = preamble try: body = self.mail_dict['body'][0] mimebody = MIMEMultipart('alternative') mimebody.attach(MIMEText(body)) mimebody.attach(MIMEText(self.body2html(), 'html')) msg.attach(mimebody) except KeyError: pass try: for filename in self.mail_dict['attach']: attachment = self.file2mime(filename) msg.attach(attachment) except KeyError: pass try: self.message_text = msg.as_bytes() except AttributeError: self.message_text = msg.as_string()
def form_message(self): """ Form an RFC822 message, with an appropriate MIME attachment """ msg = MIMEMultipart() for header in ("To", "Cc", "Bcc", "Subject", "References", "In-Reply-To"): if header.lower() in self.mail_dict: msg[header] = self.mail_dict[header.lower()][0] try: fname = os.path.split(self.mail_dict["attach"][0])[1] if "subject" not in self.mail_dict: msg["Subject"] = _("Sending %s") % fname except KeyError: pass msg.preamble = _("Mime message attached") try: body = self.mail_dict['body'][0] mimebody = MIMEMultipart('alternative') mimebody.attach(MIMEText(body)) mimebody.attach(MIMEText(self.body2html(), 'html')) msg.attach(mimebody) except KeyError: pass try: for filename in self.mail_dict['attach']: attachment = self.file2mime(filename) msg.attach(attachment) except KeyError: pass try: self.message_text = msg.as_bytes() except AttributeError: self.message_text = msg.as_string()
def create_message_with_attachment(self, options): attachment = options.get('files') attachment = attachment[0] if attachment else '' directory = os.path.split(attachment)[0] filename = os.path.basename(attachment) message = MIMEMultipart() message['to'] = options.get('to', my_email) message['from'] = options.get('sender', my_email) message['subject'] = options.get('subject', '') message_text = MIMEText(options['text']) message.attach(message_text) content_type, encoding = mimetypes.guess_type(attachment) if content_type is None or encoding is not None: content_type = 'application/octet-stream' main_type, sub_type = content_type.split('/', 1) if attachment: if main_type == 'text': fp = open(attachment, 'rb') message_text = MIMEText(fp.read(), _subtype=sub_type) fp.close() elif main_type == 'image': fp = open(attachment, 'rb') message_text = MIMEImage(fp.read(), _subtype=sub_type) fp.close() elif main_type == 'audio': fp = open(attachment, 'rb') message_text = MIMEAudio(fp.read(), _subtype=sub_type) fp.close() else: fp = open(attachment, 'rb') message_text = MIMEBase(main_type, sub_type) message_text.set_payload(fp.read()) encode_base64(message_text) fp.close() filename = os.path.basename(attachment) message_text.add_header('Content-Disposition', 'attachment', filename=filename) message.attach(message_text) return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}
def CreateMessageWithAttachment( sender, to, subject, message_text, file_dir, filename): """Create a message for an email. Args: sender: Email address of the sender. to: Email address of the receiver. subject: The subject of the email message. message_text: The text of the email message. file_dir: The directory containing the file to be attached. filename: The name of the file to be attached. Returns: An object containing a base64url encoded email object. """ message = MIMEMultipart() message['to'] = ", ".join(to) message['from'] = sender message['subject'] = subject msg = MIMEText(message_text) message.attach(msg) path = os.path.join(file_dir, filename) content_type = 'application/octet-stream' main_type, sub_type = content_type.split('/', 1) fp = open(path, 'rb') msg = MIMEBase(main_type, sub_type) msg.set_payload(fp.read()) encoders.encode_base64(msg) fp.close() msg.add_header('Content-Disposition', 'attachment', filename=filename) message.attach(msg) return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}
def construct_mail(self): """ compiles the information contained in this envelope into a :class:`email.Message`. """ # Build body text part. To properly sign/encrypt messages later on, we # convert the text to its canonical format (as per RFC 2015). canonical_format = self.body.encode('utf-8') textpart = MIMEText(canonical_format, 'plain', 'utf-8') # wrap it in a multipart container if necessary if self.attachments: inner_msg = MIMEMultipart() inner_msg.attach(textpart) # add attachments for a in self.attachments: inner_msg.attach(a.get_mime_representation()) else: inner_msg = textpart if self.sign: plaintext = inner_msg.as_bytes(policy=email.policy.SMTP) logging.debug('signing plaintext: %s', plaintext) try: signatures, signature_str = crypto.detached_signature_for( plaintext, [self.sign_key]) if len(signatures) != 1: raise GPGProblem("Could not sign message (GPGME " "did not return a signature)", code=GPGCode.KEY_CANNOT_SIGN) except gpg.errors.GPGMEError as e: if e.getcode() == gpg.errors.BAD_PASSPHRASE: # If GPG_AGENT_INFO is unset or empty, the user just does # not have gpg-agent running (properly). if os.environ.get('GPG_AGENT_INFO', '').strip() == '': msg = "Got invalid passphrase and GPG_AGENT_INFO\ not set. Please set up gpg-agent." raise GPGProblem(msg, code=GPGCode.BAD_PASSPHRASE) else: raise GPGProblem("Bad passphrase. Is gpg-agent " "running?", code=GPGCode.BAD_PASSPHRASE) raise GPGProblem(str(e), code=GPGCode.KEY_CANNOT_SIGN) micalg = crypto.RFC3156_micalg_from_algo(signatures[0].hash_algo) unencrypted_msg = MIMEMultipart( 'signed', micalg=micalg, protocol='application/pgp-signature') # wrap signature in MIMEcontainter stype = 'pgp-signature; name="signature.asc"' signature_mime = MIMEApplication( _data=signature_str.decode('ascii'), _subtype=stype, _encoder=encode_7or8bit) signature_mime['Content-Description'] = 'signature' signature_mime.set_charset('us-ascii') # add signed message and signature to outer message unencrypted_msg.attach(inner_msg) unencrypted_msg.attach(signature_mime) unencrypted_msg['Content-Disposition'] = 'inline' else: unencrypted_msg = inner_msg if self.encrypt: plaintext = unencrypted_msg.as_bytes(policy=email.policy.SMTP) logging.debug('encrypting plaintext: %s', plaintext) try: encrypted_str = crypto.encrypt( plaintext, list(self.encrypt_keys.values())) except gpg.errors.GPGMEError as e: raise GPGProblem(str(e), code=GPGCode.KEY_CANNOT_ENCRYPT) outer_msg = MIMEMultipart('encrypted', protocol='application/pgp-encrypted') version_str = 'Version: 1' encryption_mime = MIMEApplication(_data=version_str, _subtype='pgp-encrypted', _encoder=encode_7or8bit) encryption_mime.set_charset('us-ascii') encrypted_mime = MIMEApplication( _data=encrypted_str.decode('ascii'), _subtype='octet-stream', _encoder=encode_7or8bit) encrypted_mime.set_charset('us-ascii') outer_msg.attach(encryption_mime) outer_msg.attach(encrypted_mime) else: outer_msg = unencrypted_msg headers = self.headers.copy() # add Message-ID if 'Message-ID' not in headers: headers['Message-ID'] = [email.utils.make_msgid()] if 'User-Agent' in headers: uastring_format = headers['User-Agent'][0] else: uastring_format = settings.get('user_agent').strip() uastring = uastring_format.format(version=__version__) if uastring: headers['User-Agent'] = [uastring] # copy headers from envelope to mail for k, vlist in headers.items(): for v in vlist: outer_msg.add_header(k, v) return outer_msg
#!/usr/bin/env python import os import sys from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication from subprocess import Popen, PIPE attchfile = 'xxx.csv' if os.path.isfile(attchfile): print('attachment is ready to send.') _user = "******" _to = "[email protected],[email protected]" msg = MIMEMultipart() msg["Subject"] = "DataSource Usage Monthly Report" msg["From"] = _user msg["To"] = _to part = MIMEApplication(open(attchfile, 'rb').read()) part.add_header('Content-Disposition', 'attachment', filename=attachfile) msg.attach(part) p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE) p.communicate(msg.as_bytes()) else: print('The mail file seems to have a problem. Please check your code or data') sys.exit(1)
def mailsmtp(mail_from, mail_to, subject, mail_body, smtp_server, smtp_username, smtp_password, add_headers = dict(), attachments = [], mail_body_type = 'plain', smtp_security = TLS, smtp_check_certificate = True, smtp_port = PORT_25_OR_465, gpg_binary = 'gpg', gpg_options = [], gpg_recipient = [], gpg_sign = True, gpg_send_error_msg_on_error = False) : if smtp_port == PORT_25_OR_465 : smtp_port = 465 if smtp_security == TLS else 25 import sys import os import re import ssl from smtplib import SMTP_SSL # this invokes the secure SMTP protocol (port 465, uses SSL) from smtplib import SMTP # use this for standard SMTP protocol (port 25, no encryption) from email.mime.audio import MIMEAudio from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from os.path import basename from email import encoders #For guessing MIME type based on file name extension import mimetypes import subprocess try: innerMsg = MIMEMultipart() innerMsg.attach(MIMEText(mail_body, mail_body_type)) for path in attachments or []: # Guess the mail_body type based on the file's extension. Encoding # will be ignored, although we should check for simple things like # gzip'd or compressed files. ctype, encoding = mimetypes.guess_type(path) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': with open(path) as fp: # Note: we should handle calculating the charset attachinnerMsg = MIMEText(fp.read(), _subtype=subtype) elif maintype == 'image': with open(path, 'rb') as fp: attachinnerMsg = MIMEImage(fp.read(), _subtype=subtype) elif maintype == 'audio': with open(path, 'rb') as fp: attachinnerMsg = MIMEAudio(fp.read(), _subtype=subtype) else: with open(path, 'rb') as fp: attachinnerMsg = MIMEBase(maintype, subtype) attachinnerMsg.set_payload(fp.read()) # Encode the payload using Base64 encoders.encode_base64(attachinnerMsg) # Set the filename parameter attachinnerMsg.add_header('Content-Disposition', 'attachment', filename=basename(path)) innerMsg.attach(attachinnerMsg) if gpg_recipient : gpg_cmdline = [ gpg_binary ] + gpg_options + [ '--armor', '--encrypt' ] + ( [ '--sign' ] if gpg_sign else [] ) for recipient in gpg_recipient : gpg_cmdline += ['--recipient', recipient] gpgProg = subprocess.Popen(gpg_cmdline, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) gpgOut = gpgProg.communicate(innerMsg.as_bytes()) if len(gpgOut[1]) > 0: if not gpg_send_error_msg_on_error : raise Exception('GPG-call failed: ' + gpgOut[1].decode('utf-8')); else : outerMsg = MIMEMultipart() outerMsg.attach(MIMEText('GPG-call failed: ' + gpgOut[1].decode('utf-8'), 'plain')) else : outerMsg = MIMEMultipart(_subtype='encrypted', protocol="application/pgp-encrypted") encryptedMsgHeader = MIMEBase('application', 'pgp-encrypted') encryptedMsgHeader.set_payload('Version 1\n') outerMsg.attach(encryptedMsgHeader); encryptedMsg = MIMEBase('application', 'octet-stream',name="encrypted.asc") encryptedMsg.set_payload(gpgOut[0].decode('utf-8')) encryptedMsg.add_header('Content-Disposition', 'inline', filename='encrypted.asc') outerMsg.attach(encryptedMsg); else : # If there are no gpg-recipients given, the message in not encrypted and the inner message coincides with the outer message outerMsg = innerMsg outerMsg['From'] = mail_from outerMsg['Subject'] = subject outerMsg['To'] = ', '.join(mail_to); for header,value in add_headers.items() : outerMsg.add_header(header, value) ssl_context = ssl.create_default_context() if smtp_check_certificate else None if smtp_security == TLS : conn = SMTP_SSL(host=smtp_server, port=smtp_port, context=ssl_context) else : conn = SMTP(host=smtp_server, port=smtp_port) if smtp_security == STARTTLS : conn.starttls(context=ssl_context) elif smtp_security == PLAINTEXT : pass else : raise ValueError("unknown value of argument 'smtp_security'") conn.set_debuglevel(False) conn.login(smtp_username, smtp_password) try: conn.sendmail(mail_from, mail_to, outerMsg.as_string()) finally: conn.close() except Exception as exc: sys.exit( "mailsmtp failed; %s" % str(exc) ) # give a error message
login_url = "http://210.42.121.241/servlet/Login" res = session.post(login_url, headers=headers, data=post_data) if re.findall('验证码错误', res.text): print("Invalid captcha input!") else: server = smtplib.SMTP(smtp_url, 25) server.login(from_addr, pwd) msg = MIMEMultipart() message = MIMEText(captcha, "plain", "utf-8") def get_format_addr(s): name, addr = parseaddr(s) return formataddr((Header(name, "utf-8").encode(), addr)) msg["From"] = get_format_addr("Junkui Zhang <%s>" % from_addr) msg["To"] = get_format_addr("Me <%s>" % to_addr) msg["Subject"] = Header("<!CAPTCHA!>", "utf-8").encode() msg.attach(message) with open("./get_captcha/test.jpg", "rb") as f: pic = MIMEBase("image", "jpg", filename="0.jpg") pic.add_header("Content-Disposition", "attachment", filename="0.jpg") pic.add_header("Content-ID", "<0>") pic.set_payload(f.read()) encode_base64(pic) msg.attach(pic) server.sendmail(from_addr, [to_addr], msg.as_bytes()) server.close()
from email.mime.multipart import MIMEMultipart, MIMEBase from email import utils, encoders import mimetypes, sys def alternative(data, contenttype): maintype, subtype = contenttype.split('/') if maintype == 'text': retival = MIMEText(data, _subtype=subtype) else: retival = MIMEBase(maintype, subtype) retival.set_payload(data) encoders.encode_base64(retival) return retival messagetext = """Hello, This is a *great* test message from chapter 9. I hope you enjoy it! -- Anonymous""" messagehtml = """Hello, <p> This is a <b>great</b> test message from Chapter 9. I hope you enjoy it!</p> -- <i>Anonymous</i>""" msg = MIMEMultipart('alternative') msg['TO'] = '*****@*****.**' msg['From'] = 'Test Sender <*****@*****.**>' msg['Subject'] = 'Test Message, Chapter 9' msg['Date'] = utils.formatdate(localtime=1) msg['Message-ID'] = utils.make_msgid() msg.attach(alternative(messagetext, 'text/plain')) msg.attach(alternative(messagehtml, 'text/html')) print(msg.as_bytes().decode())