0

I am trying to making a python autogenerated Email app but there is a problem when running the code the traceback error shows up but I did write the code as my mentor write it down. This is the code that I used:

import datetime as dt
import random
import smtplib

MY_EMAIL = "example@yahoo.com"
MY_PASSWORD = "example"

now = dt.datetime.now()
weekday = now.weekday()

print(weekday)
if weekday == 1:
    with open("quotes.txt") as quote_file:
        all_quotes = quote_file.readlines()
        quote = random.choice(all_quotes)

    print(quote)
    with smtplib.SMTP("smtp.mail.yahoo.com") as connection:
        connection.starttls()
        connection.login(MY_EMAIL, MY_PASSWORD)
        connection.sendmail(
            from_addr=MY_EMAIL,
            to_addrs="example@gmail.com",
            msg=f"Subject:Monday Motivation\n\n{quote}"
        )

This is the error that shows:


Traceback (most recent call last):
  File "C:/Users/DP/Documents/Python Scripts/day-32-start/main.py", line 42, in <module>
1
    all_quotes = quote_file.readlines()
  File "C:\Users\DP\anaconda3\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 110: character maps to <undefined>


This is the quotes.txt file content:

“When you arise in the morning think of what a privilege it is to be alive, to think, to enjoy, to love…” – Marcus Aurelius
“Either you run the day or the day runs you.”– Jim Rohn
“Mondays are the start of the work week which offer new beginnings 52 times a year!“– David Dweck
“You've got to get up every morning with determination if you're going to go to bed with satisfaction.”– George Lorimer
“Be miserable. Or motivate yourself. Whatever has to be done, it's always your choice.”– Wayne Dyer
“Your Monday morning thoughts set the tone for your whole week. See yourself getting stronger, and living a fulfilling, happier & healthier life.”– Germany Kent
“You don’t have to be great to start, but you have to start to be great.”– Zig Ziglar
“Each morning when I open my eyes I say to myself: I, not events, have the power to make me happy or unhappy today. I can choose which it shall be. Yesterday is dead, tomorrow hasn’t arrived yet. I have just one day, today, and I’m going to be happy in it.“– Groucho Marx
“Life is full of beauty. Notice it. Notice the bumble bee, the small child, and the smiling faces. Smell the rain, and feel the wind. Live your life to the fullest potential, and fight for your dreams.”– Ashley Smith
“When you start to do the things that you truly love, it wouldn’t matter whether it is Monday or Friday; you would be so excited to wake up each morning to work on your passions.“– Edmond Mbiaka
“A ship is always safe at shore but that is not what it’s built for.”– Albert Einstein
“Stress is caused by being ‘here' but wanting to be ‘there.'– Eckhart Tolle
“People rarely succeed unless they have fun in what they are doing.”– Dale Carnegie
“Your attitude, not your aptitude, will determine your altitude.”– Zig Ziglar
“You may have to fight a battle more than once to win it.”– Margaret Thatcher
“If you don't design your own life plan, chances are you'll fall into someone else's plan. And guess what they have planned for you? Not much.”– Jim Rohn
“Try not to become a person of success, but rather try to become a person of value.”– Albert Einstein
“Morning is an important time of day, because how you spend your morning can often tell you what kind of day you are going to have.”– Lemony Snicket
“Just one small positive thought in the morning can change your whole day.”– Dalai Lama
“Think of many things; do one.”– Portuguese proverb
“One of the best pieces of advice I ever got was from a horse master. He told me to go slow to go fast. I think that applies to everything in life. We live as though there aren't enough hours in the day but if we do each thing calmly and carefully we will get it done quicker and with much less stress.”– Viggo Mortensen
“Don't let what you cannot do interfere with what you can do.”– John R. Wooden
“Success means doing the best we can with what we have. Success is the doing, not the getting; in the trying, not the triumph. Success is a personal standard, reaching for the highest that is in us, becoming all that we can be.”– Zig Ziglar
“The starting point of all achievement is desire.”– Napoleon Hill
“I was thinking one day and I realized that if I just had somebody behind me all the way to motivate me I could make a big difference. Nobody came along like that so I just became that person for myself.”–  Unknown
“If you don’t pay appropriate attention to what has your attention, it will take more of your attention than it deserves.”– David Allen”Spend eighty percent of your time focusing on the opportunities of tomorrow rather than the problems of yesterday.”– Brian Tracy
“Keep on going, and the chances are that you will stumble on something, perhaps when you are least expecting it. I never heard of anyone ever stumbling on something sitting down.”– Charles F. Kettering
“Shoot for the moon. Even if you miss, you'll land among the stars.”– Brian Littrell
“Whether you think you can or think you can’t, you’re right.”– Henry Ford
“The successful warrior is the average man, with laser-like focus.”– Bruce Lee
“The only thing worse than starting something and failing … is not starting something.”– Seth Godin
“Do not be embarrassed by your failures, learn from them and start again.”– Richard Branson
“For fast-acting relief, try slowing down. “– Lily Tomlin
“There is more to life than increasing its speed.”– Mahatma Gandhi
“It is not a daily increase, but a daily decrease. Hack away at the inessentials.”– Bruce Lee
“If I had eight hours to chop down a tree, I’d spend six hours sharpening my ax.”– Abraham Lincoln
“Keep away from people who try to belittle your ambitions. Small people always do that, but the really great make you feel that you, too, can become great.”– Mark Twain
“We can easily manage if we will only take, each day, the burden appointed to it. But the load will be too heavy for us if we carry yesterday’s burden over again today, and then add the burden of the morrow before we are required to bear it.”– John Newton
“If you want to make an easy job seem mighty hard, just keep putting off doing it.”– Olin Miller
“Winners make a habit of manufacturing their own positive expectations in advance of the event.”– Brian Tracy
“Follow effective actions with quiet reflection. From the quiet reflection will come even more effective action.”– Peter Drucker
“Don't mistake activity with achievement.”– John Wooden
“One of the symptoms of an approaching nervous breakdown is the belief that one's work is terribly important.”– Bertrand Russell
“I’ve missed more than 9000 shots in my career. I’ve lost almost 300 games. 26 times, I’ve been trusted to take the game winning shot and missed. I’ve failed over and over and over again in my life. And that is why I succeed.”– Michael Jordan
“Start where you are. Use what you have. Do what you can.”– Arthur Ashe
“Show me a person who has never made a mistake and I'll show you someone who has never achieved much.”– Joan Collins
“If you treat every situation as a life and death matter, you’ll die a lot of times.”– Dean Smith
“Amateurs sit and wait for inspiration, the rest of us just get up and go to work.”– Stephen King
“The secret of getting ahead is getting started. The secret of getting started is breaking your complex overwhelming tasks into small manageable tasks, and then starting on the first one.”– Mark Twain
“Things may come to those who wait, but only the things left by those who hustle.”– Abraham Lincoln
“People who succeed have momentum. The more they succeed, the more they want to succeed, and the more they find a way to succeed. Similarly, when someone is failing, the tendency is to get on a downward spiral that can even become a self-fulfilling prophecy.”– Tony Robbins
“I attribute my success to this: I never gave or took any excuse.”– Florence Nightingale
“Take time to deliberate; but when the time for action arrives, stop thinking and go in.”– Napoleon Bonaparte
“There is no traffic jam along the extra mile.”– Roger Staubach
“Motivation is a fire from within. If someone else tries to light that fire under you, chances are it will burn very briefly.”– Stephen R. Covey
“Success is liking yourself, liking what you do, and liking how you do it.”– Maya Angelou
“Only put off until tomorrow what you are willing to die having left undone.”– Pablo Picasso
“There are two types of people who will tell you that you cannot make a difference in this world: those who are afraid to try and those who are afraid you will succeed.”– Ray Goforth
“Everything you want is on the other side of fear.”– Jack Canfield
“Life is 10% what happens to us and 90% how we react to it.”– Dennis P. Kimbro
“You are never too old to set another goal or to dream a new dream.”– C.S. Lewis
“If you genuinely want something, don't wait for it – teach yourself to be impatient.”– Gurbaksh Chahal
“The truth is that our finest moments are most likely to occur when we are feeling deeply uncomfortable, unhappy, or unfulfilled. For it is only in such moments, propelled by our discomfort, that we are likely to step out of our ruts and start searching for different ways or truer answers.”– M. Scott Peck
“For most of life, nothing wonderful happens. If you don’t enjoy getting up and working and finishing your work and sitting down to a meal with family or friends, then the chances are you’re not going to be very happy. If someone bases his/her happiness on major events like a great job, huge amounts of money, a flawlessly happy marriage or a trip to Paris, that person isn’t going to be happy much of the time.If, on the other hand, happiness depends on a good breakfast, flowers in the yard, a drink or a nap, then we are more likely to live with quite a bit of happiness.”– Andy Rooney
“Love yourself first and everything else falls into line. You really have to love yourself to get anything done in this world.”– Lucille Ball
“We become what we think about.”– Earl Nightingale
“I don't want to get to the end of my life and find that I lived just the length of it. I want to have lived the width of it as well.”– Diane Ackerman
“New beginnings are often disguised as painful endings.”– Lao Tzu
“The universe is change; our life is what our thoughts make it.”– Marcus Aurelius
“For success, attitude is equally as important as ability.”– Harry F. Banks
“Optimism is a happiness magnet. If you stay positive, good things and good people will be drawn to you.”– Mary Lou Retton
“Don’t wait. The time will never be just right.”– Napoleon HillMonday Motivation Quote by Confucius
“It does not matter how slowly you go, so long as you do not stop.”– Confucius
“Life's real failure is when you do not realize how close you were to success when you gave up.”– Unknown
“Failure will never overtake me if my determination to succeed is strong enough.”–  Og Mandino
“When we long for life without difficulties, remind us that oaks grow strong in contrary winds and diamonds are made under pressure.”– Peter MarshallMonday Motivation Quote by Henry David Thoreau
“What you get by achieving your goals is not as important as what you become by achieving your goals.”– Henry David Thoreau
“Ever tried. Ever failed. No matter. Try Again. Fail again. Fail better.”– Samuel Beckett
“Success seems to be connected with action. Successful people keep moving. They make mistakes, but they don’t quit.”– Conrad Hilton
“Life begins at the end of your comfort zone.”– Neale Donald Walsh
“When a resolute young fellow steps up to the great bully, the world, and takes him boldly by the beard, he is often surprised to find it comes off in his hand, and that it was only tied on to scare away the timid adventurers.”– Ralph Waldo Emerson
“What seems to us as bitter trials are often blessings in disguise.”– Oscar Wilde
“Aim for success, not perfection. Never give up your right to be wrong, because then you will lose the ability to learn new things and move forward with your life. Remember that fear always lurks behind perfectionism.”– David M. Burns
“I find that the harder I work, the more luck I seem to have.”– Thomas Jefferson
“If opportunity doesn’t knock, build a door.”– Milton Berle
“You can't make positive choices for the rest of your life without an environment that makes those choices easy, natural, and enjoyable.”– Deepak Chopra
“Dreams can come true, but there is a secret. They're realized through the magic of persistence, determination, commitment, passion, practice, focus and hard work. They happen a step at a time, manifested over years, not weeks.”– Elbert Hubbard
“The past has no power over the present moment.”– Eckhart TolleMonday Motivation Quote by Unknown
“The best way to succeed in this world is to act on the advice you give to others.”– Unknown
“If you take responsibility for yourself you will develop a hunger to accomplish your dreams.”– Les Brown
“Success is not measured by what you accomplish, but by the opposition you have encountered, and the courage with which you have maintained the struggle against overwhelming odds.”– Orison Swett Marden
“Never limit yourself because of others’ limited imagination; never limit others because of your own limited imagination.”– Mae Jemison
“When I'm old and dying, I plan to look back on my life and say, ‘Wow, that was an adventure,' not, ‘Wow, I sure felt safe.'”– Tom Preston-Werner
“Our greatest fear should not be of failure but of succeeding at things in life that don't really matter.”– Francis Chan
“Nothing in the world can take the place of perseverance. Talent will not; nothing is more common than unsuccessful people with talent. Genius will not; unrewarded genius is almost legendary. Education will not; the world is full of educated derelicts. Perseverance and determination alone are omnipotent.”– Calvin Coolidge
“It takes but one positive thought when given a chance to survive and thrive to overpower an entire army of negative thoughts.”– Robert H. Schuller
“When we strive to become better than we are, everything around us becomes better too.”– Paulo Coelho
“Twenty years from now you will be more disappointed by the things that you didn't do than by the ones you did do. So throw off the bowlines. Sail away from the safe harbor. Catch the trade winds in your sails. Explore. Dream. Discover.”– Mark Twain
“A year from now you may wish you had started today.”– Karen Lamb
“To laugh often and much; to win the respect of intelligent people and the affection of children… to leave the world a better place… to know even one life has breathed easier because you have lived. This is to have succeeded.”– Ralph Waldo Emerson
“Don’t brood. Get on with living and loving. You don’t have forever.”– Leo Buscaglia

I will be very glad if anyone can help me with this problem thank you very much.

  • 4
    Don't share sensitive info...you are sharing your password of your email account....so kindly remove it – Anurag Dabas May 18 '21 at 03:05
  • 1
    You are running on Windows. You have an 8-bit (non-Unicode) file, and it contains characters that are not in the standard Windows character set (CP1252). You will need to know what character set the file contains. – Tim Roberts May 18 '21 at 03:06
  • If the password you originally provided was real make sure to change it as it would now be definitely compromised. – michaeldel May 18 '21 at 03:09
  • 1
    Please share any personal information on a public forum. Make sure to remove it. – Alok Raj May 18 '21 at 05:53
  • Thanks for editing it. I forgot to remove the personal information.... next time I will be aware of it. Thank You very much michaelder. – Ashraful Islam Joy May 18 '21 at 13:45

2 Answers2

1

Your quotes.txt file seems to be corrupted.

You can easily convert this to utf8 Unicode from PowerShell using below command: -

Get-Content .\test.txt | Set-Content -Encoding utf8 test-utf8.txt

you can also use applications like notepad, notepad++ etc. to convert file to utf8 encoding

Windows (Notepad)
   -> Open Notepad.
   -> File - Save as -> there you see 3 fields set the last one called "encoding" to: UTF-8.

If the above things don't work, it means that the message to be sent contains non-ASCII characters and to handle that there are two ways : -

  1. Using EmailMessage() . I read this in some articles but it didn't work for me as I was using smtp.gmail.com which needed SMTP_SSL function to be used for ssl connection instead of SMTP. For reference please take a look here : - SMTP EmailMessage()

  2. The Second method is by using MIMEText. This eventually worked for me. As we want to send some non-ASCII characters in the message, sending it using MIMEMultipart seems to be the best option to be me personally, with content-type as plain text. ( One can combine html and plain text in the mail if they want, by attaching new MMIText with different content-type)

Below is the code for the same: -

import datetime as dt
import random
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

MY_EMAIL = "FROM@gmail.com"
MY_PASSWORD = "PASSWORD"

now = dt.datetime.now()
weekday = now.weekday()

print(weekday)
if weekday == 1:
    with open("quotes.txt") as quote_file:
        all_quotes = quote_file.readlines()
        quote = random.choice(all_quotes)

    print(quote)
    server_ssl = smtplib.SMTP_SSL("smtp.gmail.com", 465)
    server_ssl.ehlo()
    server_ssl.login(MY_EMAIL, MY_PASSWORD)
    msg = MIMEMultipart()
    msg['From'] = MY_EMAIL
    msg['To'] = ", ".join("TO@gmail.com")
    msg['Subject'] = 'Test Automation Email'
    msg.attach(MIMEText(quote, 'plain'))
    text = msg.as_string()
    server_ssl.sendmail(MY_EMAIL, "TO@gmail.com", text)
    server_ssl.quit()
print('Email sent successfully')

References:-

https://superuser.com/questions/1163753/converting-text-file-to-utf-8-on-windows-command-prompt https://docs.moodle.org/2x/pl/Converting_files_to_UTF-8

Please feel free to reach out in the comments for any help.

Happy to help !!!

Alok Raj
  • 447
  • 2
  • 11
  • Thanks for Answering. The solution you give I done it properly. First, give the code in the terminal and address the quotes.txt file it also converted to utf8 and I give the directory to the new txt-utf8.txt file in my code after running it shows traceback error again. UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 110: character maps to – Ashraful Islam Joy May 18 '21 at 14:01
  • If possible can you shre me the quotes.txt content. Or can you try with some dummy text to send. This way we can debug easily if the file is corrupted – Alok Raj May 18 '21 at 14:08
  • Ok I am sharing the txt file in the post. – Ashraful Islam Joy May 18 '21 at 14:12
  • Which operating system are you using ? Windows 10 , 8, 7 ?? and what is your python version – Alok Raj May 18 '21 at 14:24
  • Windows 10 , Python 3.8.5 – Ashraful Islam Joy May 18 '21 at 14:25
  • If you not much concerned of this particular error, then there is a provision in python to ignore these characters while reading your file, which I personally use in some of my own applications . For this you can replace this line *** with open("quotes.txt") as quote_file *** with the below one *** with codecs.open("quotes.txt", 'r', encoding='utf-8', errors='ignore') as quote_file:*** And do import codecs on the top – Alok Raj May 18 '21 at 14:28
  • Same error only show one line of the quote. Traceback (most recent call last): File "c:/Users/DP/Documents/Python Scripts/day-32-start/main.py", line 50, in connection.sendmail( File "C:\Users\DP\AppData\Local\Programs\Python\Python38\lib\smtplib.py", line 859, in sendmail msg = _fix_eols(msg).encode('ascii') UnicodeEncodeError: 'ascii' codec can't encode character '\u201c' in position 29: ordinal not in range(128) PS C:\Users\DP\Documents\Python Scripts\day-32-start> – Ashraful Islam Joy May 18 '21 at 14:39
  • Give me sometime, will resolve this – Alok Raj May 18 '21 at 14:40
  • Thank you very much for your valuable time boss. – Ashraful Islam Joy May 18 '21 at 14:42
  • Found a soultion finally, will post – Alok Raj May 18 '21 at 16:53
  • Where the post is? – Ashraful Islam Joy May 18 '21 at 17:11
  • Have edited my post, please refer that. I literally installed windows for replicating your issue :p lol But I am happy to resolve it :) – Alok Raj May 18 '21 at 17:33
  • Thank you very much for answering this boss... – Ashraful Islam Joy May 19 '21 at 04:07
  • nps :) Happy to help – Alok Raj May 19 '21 at 04:17
0

Try and set the encoding to UTF-8

For example:

file = open(filename, encoding="utf8")

For reference check this post:

UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

Brian Ross
  • 11
  • 3
  • Thanks for your answer. It printed only 1 line of the quote but later quote was not able to decode terminal show me this error. Traceback (most recent call last): File "c:/Users/DP/Documents/Python Scripts/day-32-start/main.py", line 49, in connection.sendmail( File "C:\Users\DP\AppData\Local\Programs\Python\Python38\lib\smtplib.py", line 859, in sendmail msg = _fix_eols(msg).encode('ascii') UnicodeEncodeError: 'ascii' codec can't encode character '\u201c' in position 29: ordinal not in range(128) PS C:\Users\DP\Documents\Python Scripts\day-32-start> – Ashraful Islam Joy May 18 '21 at 14:07