Print Email body using imap_tools in python - python

I've been trying to print email body using python(using imap_tools lib)but it's not really working for me. here is the code snippet.
from imap_tools import MailBox, A, AND, OR, NOT
with MailBox('outlook.office365.com').login('test#test.com', 'test') as mailbox:
for msg in mailbox.fetch(A(seen=False)):
print(msg.text)
but when I print the subject using msg.subject, it's working fine. I tried using msg.html and here is the output.
<body lang="EN-IN" link="blue" vlink="#954F72" style="word-wrap:break-word"><div class="WordSection1"><p class="MsoNormal">Hi, this is a test email to store body in file<o:p></o:p></p></div></body></html>
note: this is not the whole HTML output, but this is to show that the email has some data in the body.
Can anyone help me solve this problem?

Related

[Python]Why are email pdf attachments not showing up on Outlook/Thunderbird, while they do on Gmail? (Sent from a Python environment)

I've just joined a project and have been trying to figure why some emails are showing up as they should on Gmail but when I open then with a client like Thunderbird or Outlook the attached PDFs do now show up.
As an additional detail if I forward the mail from Thunderbird/Tutlook to a Gmail account the attached pdf will appear and if I send it back to the Thunderbird/Outlook - connected account it will again appear, so Gmail fixes something that's wrong in the code.
This is my second time dealing with emails, the first being mostly copying some code to see if it works, so if you're willing to explain it to me in addition to helping me fix it, I'd appreciate it greatly.
I'll post the code here and then add some additional information on what I tried below, to keep this a bit cleaner.
So, here's the code:
from email.message import EmailMessage
from email import encoders
from email.mime.base import MIMEBase
import smtplib
msg = EmailMessage()
msg['Subject'] = subject
msg['From'] = "someaddress"
msg['To'] = user_email
msg.set_content('Certification')
msg.add_alternative("""<!DOCTYPE html>
<html>
<body>
Stuff...
</body>
</html>
""", subtype='html')
filename = 'somefilename'
pdf_filename = 'certificate.pdf'
with open(filename, "rb") as attachment:
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header(
"Content-Disposition",
"attachment", filename=pdf_filename
)
try:
msg.attach(part)
with smtplib.SMTP('someIP', port) as smtp:
smtp.send_message(msg)
I've seen some similar issues (or actually the same issue) before, and some solutions suggested using a MIMEMultipart-mixed message object instead of an email one like this:
msg=MIMEMultipart('mixed') instead of msg = EmailMessage() but because add_alternative is not a MIMEMultipart method, I cannot do that without changing that part.
(The above was suggested on this post - which is exactly the same issue as mine, but unfortunately I could not use the same fix)
What I tried doing was calling a
msg.make_mixed() below msg=Email.Message() hoping that the mixed type (I don't understand email types yet) would solve the problem, but when I tried sending an email that way I got a Status=4, Failed to send file, error.
I would also really appreciate if you could offer any suggestion for a resource to learn some more about sending and receiving emails (from a python perspective).
Thank you!
The problem here is that you have directly attached a pre-built MIME part to a multipart/alternative message. It ends in an incorrect message that may be poorly processed by mail readers.
In the email.message interface, you should use the add_attachement method. It will handle the base64 encoding and will change the message into a multipart/mixed one:
with open(filename, "rb") as attachment:
msg.add_attachment(attachment.read(), maintype='application',
subtype='octet-stream', filename=pdf_filename)
try:
with smtplib.SMTP('someIP', port) as smtp:
smtp.send_message(msg)

Python exchangelib - How to Capture/Save email as png

Need your assistance in saving the email as .png. The code below will get the body of the email, but it is unable to get a screenshot in the body of the email.
with open(r"output.txt", "w") as output:
for item in fromfolder.filter(is_read=False):
output.write('{}\n'.format(item.body))
item.is_read = True
item.save()
item.move(archieve)
Have tried saving email as eml and msg, but nothing is working out.
item.body contains the entire body of the email message, not just the image contained in the body.
exchangelib does not offer methods to parse the body of the email. You'll need to use other packages for that.
I think your best bet would be to parse the item.mime_content field which contains the raw email content. You can use e.g. email.parser.BytesParser.parse_bytes(mime_content) from https://docs.python.org/3/library/email.parser.html. This will return an EmailMessage with your PNG image.

How to send hyperlink with SendGrid using Python

I'm trying to send a simple mail with SendGrid which must contain one hyperlink.
I'm not doing anything fancy, just following the documentation example with some changes
import os
from sendgrid.helpers.mail import *
sg = sendgrid.SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY'))
from_email = Email("test#example.com")
to_email = To("test#example.com")
subject = "Sending with SendGrid is Fun"
content = Content("text/html", '<html>google</html>')
mail = Mail(from_email, to_email, subject, content)
response = sg.client.mail.send.post(request_body=mail.get())
It looks fine to me, but once I run the script and the mail is sent, it shows up like plain text I cannot click on.
I also tried many other combinations removing the <html> tag, using single and double quotes with the backslash, but nothing really worked. I even tried to do the same thing without the Mail Helper Class, but it didn't work.
Thanks very much for the help.
content = Content(
"text/html", "Hi User, \n This is a test email.\n This is to also check if hyperlinks work <a href='https://www.google./com'> Google </a> Regards Karthik")
This helped me. I believe you don't need to mention the html tags

How do I log into Google through python requests?

I'm making an API using Python requests, and HTTP GET is working fine, but I'm having a little bit of trouble with HTTP POST. So, as with a lot of websites, you can read information, but in order to make a post request (such as following a user, or writing a post), you need to have an authenticated session. THIS website, uses google to log in. Normally, I would just pass the username:password into the POST request formdata to log in, but this google thing is pretty wonky (and quite frankly I'm not that experienced). Does anyone have a reference or an example to help me out? ;/
I do not know about python requests but to send an email its as easy as this
import yagmail
yagmail.SMTP(emailh).send(email, subject, body)
#emailh = your email (just username no #gmail.com)
#email = send to (full email including domain ***#gmail.com or ***#outlook.com)
#subject = subject of the message
#body = body of the message
Even better
emailh = raw_input('Your email: ')
email = raw_input('Send to: ')
subject = raw_input('Subject: ')
body = raw_input('Body: ')
yagmail.SMTP(emailh).send(email, subject, body)
print('Email Sent.')
If this is what you are talking about anyway.
This page might be useful link

What fields are available after parsing an email message?

I am using email.message_from_string to parse an email message into Python. The documentation doesn't seem to say what standard fields there are.
How do I know what fields are available to read from, such as msg['to'], msg['from'], etc.? Can I still find this if I don't have an email message to experiment with on the command line?
email.message_from_string() just parses the headers from the email. Using keys() you get all present headers from the email.
import email
e = """Sender: test#test.dk
From: test#test.dk
HelloWorld: test
test email
"""
a = email.message_from_string(e)
print a.keys()
Outputs: ['Sender', 'From', 'HelloWorld']
Therefore, you will never find a manual that includes from, to, sender etc. as they are not part of the API, but just parsed from the headers.

Categories

Resources