def write_text(self, content: str, content_type: str, encoding: str, file_info: FileInfo) -> None: encoded_content = content.encode(encoding) policy = email.policy.compat32.clone(linesep='\n', max_line_length=0, cte_type='8bit', raise_on_defect=True) message = email.message.Message(policy) if file_info.version is not None: message.add_header('Version', str(file_info.version)) if file_info.filetype is not None: message.add_header('File-Type', file_info.filetype) message.add_header('Checksum', hashlib.md5(encoded_content).hexdigest(), type='md5') message.add_header('Content-Type', content_type, charset=encoding) message.add_header('Content-Length', str(len(encoded_content))) with open(self.path, 'wb') as fp: fp.write(self.MAGIC) fp.write(message.as_bytes()) fp.write(encoded_content)
def test_prefer_html_over_text(self): message = self.get_message_html_plain('Text Alternative1', 'hypertext1', 'plaintext1') self.inject_mail(self.gestalt.user.email, [self.group_address], data=message.as_bytes()) contribution = self.assertExists(models.Contribution, conversation__subject='Text Alternative1', text__text='hypertext1') self.assertEqual(contribution.attachments.count(), 0)
def main(args): message = email.message.EmailMessage(email.policy.SMTP) message['To'] = 'Test Recipient <*****@*****.**>' message['From'] = 'Test Sender <*****@*****.**>' message['Subject'] = 'Foundations of Python Network Programming' message['Date'] = email.utils.formatdate(localtime=True) message['Message-ID'] = email.utils.make_msgid() if not args.i: message.set_content(html, subtype='html') message.add_alternative(plain) else: cid = email.utils.make_msgid() # RFC 2392: must be globally unique! message.set_content(html + img.format(cid.strip('<>')), subtype='html') message.add_related(blue_dot, 'image', 'gif', cid=cid, filename='blue-dot.gif') message.add_alternative(plain) for filename in args.filename: mime_type, encoding = mimetypes.guess_type(filename) if encoding or (mime_type is None): mime_type = 'application/octet-stream' main, sub = mime_type.split('/') if main == 'text': with open(filename, encoding='utf-8') as f: text = f.read() message.add_attachment(text, sub, filename=filename) else: with open(filename, 'rb') as f: data = f.read() message.add_attachment(data, main, sub, filename=filename) sys.stdout.buffer.write(message.as_bytes())
def write_text(self, content, content_type, encoding, file_info): content = content.encode(encoding) policy = email.policy.compat32.clone( linesep='\n', max_line_length=0, cte_type='8bit', raise_on_defect=True) message = email.message.Message(policy) if file_info.version is not None: message.add_header('Version', str(file_info.version)) if file_info.filetype is not None: message.add_header('File-Type', file_info.filetype) message.add_header('Checksum', hashlib.md5(content).hexdigest(), type='md5') message.add_header('Content-Type', content_type, charset=encoding) message.add_header('Content-Length', str(len(content))) with open(self.path, 'wb') as fp: fp.write(self.MAGIC) fp.write(message.as_bytes()) fp.write(content)
def sendEmailSMTP(fmail, password, tmail_list, message, append=False): """ :param fmail: 发件账户地址 :param password: 发件账户密码 :param tmail_list: 收件人列表 :param message: 结构化邮件消息 :param append: 是否将该邮件加入服务器已发送文件夹(默认为否) :return mailstate: 发件结果 """ mail_host = 'smtp.' + fmail.split('@')[-1] #print('ready to send') try: #print('start try') smtpObj = smtplib.SMTP_SSL(mail_host, 465) smtpObj.login(fmail, password) #print('logged') smtpObj.sendmail(fmail, tmail_list, message.as_string()) mailstate = '邮件发送成功\n' smtpObj.close() except: mailstate = '邮件发送失败\n' if append: imapObj = imaplib.IMAP4_SSL(mail_host) imapObj.login(fmail, password) imapObj.append('Sent', '\\Recent', 0, message.as_bytes()) mailstate += '邮件已经加入 已发送 文件夹\n' imapObj.logout() return mailstate
def assemble_mail_data(self, headers, body=None): message = email.message.Message() for key, value in headers.items(): message.add_header(key, value) if body: message.set_payload(body) return message.as_bytes()
def mail_changes(config, changes, subject): ALCLog.info( _("Mailing %(address)s: %(subject)s") % { 'address': config.email_address, 'subject': subject }) charset = email.charset.Charset('utf-8') charset.body_encoding = '8bit' charset.header_encoding = email.charset.QP message = email.message.Message() if config.email_format == 'html': changes = html(config).convert_to_html(subject, changes) message['Content-Type'] = 'text/html; charset=utf-8' message['Auto-Submitted'] = 'auto-generated' message['Subject'] = email.header.Header(subject, charset) message['To'] = config.email_address message.set_payload(changes, charset) try: subprocess.run(['/usr/sbin/sendmail', '-oi', '-t'], input=message.as_bytes(), check=True) except Exception as ex: ALCLog.warning( _("Failed to send mail to %(address)s: %(errmsg)s") % { 'address': config.email_address, 'errmsg': ex })
def main(args): message = email.message.EmailMessage(email.policy.SMTP) message['To'] = 'Test Recipient <*****@*****.**>' message['From'] = 'Test Sender <*****@*****.**>' message['Subject'] = 'Foundations of Python Network Programming' message['Date'] = email.utils.formatdate(localtime=True) message['Message-ID'] = email.utils.make_msgid() if not args.i: message.set_content(html, subtype='html') message.add_alternative(plain) else: cid = email.utils.make_msgid() # RFS 2392: must be globally unique! message.set_content(html + img.format(cid.strip('<>')), subtype='html') message.add_related(blue_dot, 'image', 'gif', cid=cid, filename='blue-dot.gif') message.add_alternative(plain) for filename in args.filename: mime_type, encoding = mimetypes.guess_type(filename) if encoding or (mime_type is None): mime_type = 'application/octet-stream' main, sub = mime_type.split('/') if main == 'text': with open(filename, encoding='utf-8') as f: text = f.read() message.add_attachment(text, sub, filename=filename) else: with open(filename, 'rb') as f: data = f.read() message.add_attachment(data, main, sub, filename=filename) sys.stdout.buffer.write(message.as_bytes())
def main(): message = email.message.EmailMessage(email.policy.SMTP) message['To'] = 'Böðvarr <*****@*****.**>' message['From'] = 'Eardstapa <*****@*****.**>' message['Subject'] = 'Four lines from The Wanderer' message['Date'] = email.utils.formatdate(localtime=True) message.set_content(text, cte='quoted-printable') sys.stdout.buffer.write(message.as_bytes())
def test_handle_plain_only(self): message = email.message.EmailMessage() message.add_header('subject', 'Plain Only') plain_content = '<p>HTML tags should be ignored, here.</p>' message.set_content(plain_content) self.inject_mail(self.gestalt.user.email, [self.group_address], data=message.as_bytes()) self.assertExists(models.Contribution, conversation__subject='Plain Only', text__text=plain_content)
def test_html_conversion_simple_list(self): message = email.message.EmailMessage() message.add_header('subject', 'HTML Only') message.make_alternative() message.add_alternative('<ul><li>foo</li><li>bar</li></ul></p>', 'html') self.inject_mail(self.gestalt.user.email, [self.group_address], data=message.as_bytes()) self.assertExists(models.Contribution, conversation__subject='HTML Only', text__text=' * foo\n * bar')
def test_plain_signature_removal(self): message = email.message.EmailMessage() message.add_header('subject', 'With Signature') plain_content = 'foo\nbar\n-- \nbaz\n-- \nfuz' message.set_content(plain_content) self.inject_mail(self.gestalt.user.email, [self.group_address], data=message.as_bytes()) self.assertExists(models.Contribution, conversation__subject='With Signature', text__text='foo\nbar')
def main(): message = email.message.EmailMessage(email.policy.SMTP) message['To'] = '*****@*****.**' message['From'] = 'Test Sender <*****@*****.**>' message['Subject'] = 'Test Message, Chapter 12' message['Date'] = email.utils.formatdate(localtime=True) message['Message-ID'] = email.utils.make_msgid() message.set_content(text) sys.stdout.buffer.write(message.as_bytes())
def main(): message = email.message.EmailMessage(email.policy.SMTP) message["To"] = "*****@*****.**" message["From"] = "Test Sender <*****@*****.**>" message["Subject"] = "Test Message, Chapter 12" message["Date"] = email.utils.formatdate(localtime=True) message["Message-ID"] = email.utils.make_msgid() message.set_content(text) sys.stdout.buffer.write(message.as_bytes())
def deliver(self, message, recipients, sender): relay_host = self.configure_relay() self.log_delivery(message, recipients, sender) try: data = _fix_eols(message.as_bytes()) relay_host.sendmail(sender, recipients, data) finally: try: relay_host.quit() except smtplib.SMTPServerDisconnected: pass
def test_attachment_text_is_stored(self): message = self.get_message_html_plain('Text Alternative3', 'hypertext3', 'plaintext3') content = b'attached-text' message.add_attachment(content, maintype='text', subtype='plain') self.inject_mail(self.gestalt.user.email, [self.group_address], data=message.as_bytes()) contribution = self.assertExists(models.Contribution, conversation__subject='Text Alternative3', text__text='hypertext3') self.assertEqual(contribution.attachments.count(), 1) file_obj = contribution.attachments.first().file.first() self.assertEqual(file_obj.file.size, len(content))
def main(): #EmailMessage类python提供用于构造电子邮件信息的最基本的接口 message = email.message.EmailMessage(email.policy.SMTP) message['To'] = '*****@*****.**' message['From'] = 'Test sender <*****@*****.**>' message['Subject'] = 'The Message is what I want to say before I die' #返回本地时间作为已知的日期时间对象。 message['Date'] = email.utils.formatdate(localtime=True) #email.utils.make_msgid(idstring = None,domain = None)返回适合 符合RFC 2822的 Message-ID标头。 message['Message-ID'] = email.utils.make_msgid() #调用content_manager的方法,将self作为消息对象传递,并将其他任何参数或关键字作为附加参数传递。 message.set_content(text) #标准输出的缓冲区中写东西 sys.stdout.buffer.write(message.as_bytes())
def send_message(self, message: email.message.EmailMessage) -> str: """Sends a message. Args: - message (email.message.EmailMessage): Message to send Raises: - RuntimeError: Cannot send email Returns: - str: ID of the message, as given by Google Mail API """ payload = {"raw": base64.urlsafe_b64encode(message.as_bytes()).decode()} res = self.getService().users().messages().send(userId=self._sender, body=payload).execute() if "id" not in res: raise RuntimeError("Could not send email: {}".format(message.items())) return res["id"]
def send_emails(text): # Foundations of Python network Programming, Third Edition # https://github.com/brandon-rhodes/fonp/bvlob/m/py3/chapter12/build_bhasic_email.py # text = """Hello, # This is a basic message from Chapter 12. # - Anonymous""" message = email.message.EmailMessage(email.policy.SMTP) message['To'] = '*****@*****.**' message['From'] = 'Test Sender <*****@*****.**>' message['Subject'] = 'Test Message, Chapter 12' message['Date'] = email.utils.formatdate(localtime=True) message['Message-ID'] = email.utils.make_msgid() message.set_content(text) sys.stdout.buffer.write(message.as_bytes())
def informar_posible_copia(msg, text): """ Funcion que envia un mensaje al autor de msg de parte del destinatario""" service = autenticar() message = MIMEText(text) message['to'] = "*****@*****.**" message['from'] = msg['To'] message['subject'] = "Posible copia detectada en el corrector" raw = base64.urlsafe_b64encode(message.as_bytes()) raw = raw.decode() msj = {'raw': raw} try: enviado = (service.users().messages().send(userId=user_id, body=msj).execute()) print('Message Id: %s' % enviado['id']) except errors.HttpError as error: print('An error occurred: %s' % error)
def responder(msg, text): """ Funcion que envia un mensaje al autor de msg de parte del destinatario""" service = autenticar() message = MIMEText(text) message['to'] = msg['From'] message['from'] = msg['To'] message['subject'] = "Re: " + msg['Subject'] raw = base64.urlsafe_b64encode(message.as_bytes()) raw = raw.decode() msj = {'raw': raw} try: enviado = (service.users().messages().send(userId=user_id, body=msj).execute()) print('Message Id: %s' % enviado['id']) except errors.HttpError as error: print('An error occurred: %s' % error)
def test_attachment_image_is_stored(self): message = self.get_message_html_plain('Text Alternative2', 'hypertext2', 'plaintext2') content = b'image-data' message.add_attachment(content, maintype='image', subtype='png') for part in message.walk(): if part.get_content_type() == 'image/png': part.replace_header('Content-Disposition', 'attachment; filename="foo.baz.png"') self.inject_mail(self.gestalt.user.email, [self.group_address], data=message.as_bytes()) contribution = self.assertExists(models.Contribution, conversation__subject='Text Alternative2', text__text='hypertext2') self.assertEqual(contribution.attachments.count(), 1) file_obj = contribution.attachments.first().file.first() self.assertEqual(file_obj.file.size, len(content)) # the check is only based on the content disposition (filename) self.assertTrue(file_obj.is_image()) short_filename = os.path.basename(file_obj.file.path) self.assertTrue(short_filename.startswith('foo.baz-'), file_obj.file.path) self.assertTrue(short_filename.endswith('.png'), file_obj.file.path)
def create_checkpoint(self): policy = email.policy.compat32.clone( linesep='\n', max_line_length=0, cte_type='8bit', raise_on_defect=True) message = email.message.Message(policy) message['Version'] = str(self.VERSION) message['Content-Type'] = 'application/json; charset=utf-8' checkpoint = json.dumps( self.serialize(), ensure_ascii=False, indent=' ', sort_keys=True, cls=JSONEncoder) serialized_checkpoint = checkpoint.encode('utf-8') message.set_payload(serialized_checkpoint) checkpoint_data = message.as_bytes() self.storage.add_checkpoint(checkpoint_data)
def serialize_command(self, cmd, target_id, now): serialized = json.dumps( cmd.serialize(), ensure_ascii=False, indent=' ', sort_keys=True, cls=JSONEncoder) policy = email.policy.compat32.clone( linesep='\n', max_line_length=0, cte_type='8bit', raise_on_defect=True) message = email.message.Message(policy) message['Version'] = str(self.VERSION) message['Content-Type'] = 'application/json; charset=utf-8' message['Target'] = target_id message['Time'] = time.ctime(now) message['Timestamp'] = '%d' % now message.set_payload(serialized.encode('utf-8')) return message.as_bytes()
def append(self, content, entry_type, content_type, encoding='utf-8', headers=None): policy = email.policy.compat32.clone( linesep='\n', max_line_length=0, cte_type='8bit', raise_on_defect=True) message = email.message.Message(policy) content = content.encode(encoding) message.add_header('Checksum', hashlib.md5(content).hexdigest(), type='md5') message.add_header('Content-Type', content_type, charset=encoding) message.add_header('Content-Length', str(len(content))) if headers is not None: # pragma: no branch for key, value in headers.items(): message.add_header(key, str(value)) super().append(message.as_bytes() + content, entry_type)
def main(args): #EmailMessage类python提供用于构造电子邮件信息的最基本的接口 message = email.message.EmailMessage(email.policy.SMTP) message['To'] = 'Test Recipient <*****@*****.**>' message['From'] = 'Test Sender <*****@*****.**>' message['Subject'] = 'Foundations of Python Network Programming' #返回本地时间作为已知的日期时间对象。 message['Date'] = email.utils.formatdate(localtime=True) #email.utils.make_msgid(idstring = None,domain = None)返回适合 符合RFC 2822的 Message-ID标头。 message['Message-ID'] = email.utils.make_msgid() if not args.i: #set_content()用来设置消息主体 message.set_content(html, subtype='html') message.add_alternative(plain) else: cid = email.utils.make_msgid() message.set_content(html + img.format(cid.strip('<>')), subtype='html') #add_related()方法用于向主要内容添加生成消息所用的其他资源。通常主要内容为HTML,并且需要图片,css,javascript时会使用此方法 message.add_related(blue_dot, 'image', 'gif', cid=cid, filename='blue-dot.gif') #以下方法提供其他格式的电子邮件信息 message.add_alternative(plain) for filename in args.filename: #根据文件名,路径或URL(由url给出)来猜测文件的类型。返回值是一个元组(type, encoding) #其中type是无法猜测的类型(缺少或后缀未知)或形式为的字符串 mime_type, encoding = mimetypes.guess_type(filename) if encoding or (mime_type is None): mime_type = 'application/octet-stream' main, sub = mime_type.split('/') if main == 'text': with open(filename, encoding='utf-8') as f: text = f.read() #以下方法用于提供附件,如PDF文件,图片以及电子表格 message.add_attachment(text, sub, filename=filename) else: with open(filename, 'rb') as f: data = f.read() message.add_attachment(data, main, sub, filename=filename) sys.stdout.buffer.write(message.as_bytes())
def read_email(folder, output): with (folder / 'InternetHeaders.txt').open('rb') as f: raw_headers = f.read() message = email.message_from_bytes(raw_headers) del message['Content-Type'] message.set_payload(None) message['Content-Type'] = 'multipart/mixed' html_file = folder / 'Message.html' text_file = folder / 'Message.txt' if html_file.exists(): with html_file.open('rb') as f: html_src = f.read() utf8 = bool(re.search(br'charset\s*=["\']?utf[-]?8', html_src[:1024])) params = {'charset': 'utf-8'} if utf8 else {} html = MIMEBase('text', 'html', **params) html.set_payload(html_src) email.encoders.encode_base64(html) message.attach(html) elif text_file.exists(): text = MIMEBase('text', 'plain') with text_file.open('rb') as f: text.set_payload(f.read()) email.encoders.encode_base64(text) message.attach(text) attachments_dir = folder / 'Attachments' if attachments_dir.exists(): for p in attachments_dir.iterdir(): if p.is_dir(): for i in p.iterdir(): if i.name.startswith('Message'): message.attach(get_message_attachment(i)) else: raise RuntimeError('unknown attachment {!r}'.format(i)) else: message.attach(get_file_attachment(p)) output.write(message.as_bytes())
def append(self, content: str, entry_type: bytes, content_type: str, encoding: str = 'utf-8', headers: Optional[Dict[str, Any]] = None) -> None: policy = email.policy.compat32.clone(linesep='\n', max_line_length=0, cte_type='8bit', raise_on_defect=True) message = email.message.Message(policy) encoded_content = content.encode(encoding) message.add_header('Checksum', hashlib.md5(encoded_content).hexdigest(), type='md5') message.add_header('Content-Type', content_type, charset=encoding) message.add_header('Content-Length', str(len(encoded_content))) if headers is not None: # pragma: no branch for key, value in headers.items(): message.add_header(key, str(value)) self.__file.append(message.as_bytes() + encoded_content, entry_type)
import email.message, email.utils, email.policy, sys from pprint import pprint import socket info = socket.getaddrinfo('www.google.com', 'telnet', 0, socket.SOCK_STREAM, 0, socket.AI_PASSIVE) pprint(info) respons = str(info) message = email.message.EmailMessage(email.policy.SMTP) message['To'] = "*****@*****.**" message['From'] = 'Test message <*****@*****.**>' message['Subject'] = 'this is test using python' message['Date'] = email.utils.formatdate(localtime=True) message['message-id'] = email.utils.make_msgid() message.set_content(respons) sys.stdout.buffer.write(message.as_bytes())