mail-client issue in Python - python

My script should take the user inputs and login to the server but when I give it the inputs it false and I tried different servers and different emails and the passwords are correct. How can I determine what's wrong?
import smtplib
sent = 'true'
ss = 'true'
repeat = 1
while sent == 'true':
m_email = input ('Enter Your Email Address: ')
m_server = input ('Entere Your Email Server: ')
m_auth = input ('username?\n')
p_auth = input ('password?\n')
r_email = input ('enter the reciver email: ')
subject = input ('enter Your Subject: ')
subject = 'subject '+ subject
m_massege = input ('Your Massege: ')
massege = subject + '\n \n' + m_massege
while ss == 'true' or repeat == "5" :
try:
server = smtplib.SMTP(m_server)
server.ehlo()
server.starttls()
server.login(m_auth,p_auth)
server.Sendmail(m_email,r_mail,massege)
print ("Mail Sent Successfully!")
sent = 'false'
except:
print ('sending failed')
repeat =+ 1
exit()

I've also had issues with smtplib and what I found was that it was not actually a code issue but rather an issue with the email account. For example, in my case I was trying to log into my yahoo mail account to automate emails and it kept failing so I had to go to my yahoo account security settings and enable "allow unsecured application login".
Point is: the problem isn't with your code but with the security settings on the email accounts (For me neither gmail nor yahoo worked).

Related

Setting email alert between 108300 and 108500

I am fairly new to Python coding and need some help, I am trying to implement email sending when a scale gets to weights between 10839 and 10850
I know I can use w>10840 and anything above this will trigger an email but the hx711 connected to the pi occasionally spikes causing a false email to be sent so I need it to only send emails when the weight is between 10839 and 10850.
Here is a sample of the code I am using, note I used == but as the pi updates every 5 seconds I have found it can bypass the exact weight without setting off an email. That's why I want to set more of a range
if w==10840:
if flag == 0:
lcdclear()
lcdprint("Fuel Cell Has Been Replenished")
setCursor(0,1);
lcdprint("Sending Email")
server = smtplib.SMTP('mail.jon2.com', 587)
server.starttls()
server.login("jon2#jon2.com", "aaaa1111")
msg = "Fuel Cell Has Been Replenished"
server.sendmail("jon1#jon2.co.uk", msg)
server.quit()
To check if value is between a range you can use this:
if 10839 < w < 10850:
if flag == 0:
lcdclear()
lcdprint("Fuel Cell Has Been Replenished")
setCursor(0,1);
lcdprint("Sending Email")
server = smtplib.SMTP('mail.jon2.com', 587)
server.starttls()
server.login("jon2#jon2.com", "aaaa1111")
msg = "Fuel Cell Has Been Replenished"
server.sendmail("jon1#jon2.co.uk", msg)
server.quit()

Line breaks in SMTPLIB Python 3

I am trying to make a script that sends a email. But how to do line breaks? I tried the following:
Change msg = MIMEText(msginp) to msg=MIMEText(msginp,_subtype='plain',_charset='windows-1255')
NOTE: msginp is a input (msginp = input('Body? '))
Does anybody know how to make line breaks? Like the enter key on your keyboard?
My code is:
import smtplib
from email.mime.text import MIMEText
import getpass
smtpserverinp = input('What SMTP server are you using? (Look here for more information. https://sites.google.com/view/smtpserver) ')
usern = input('What is your email adderess? ')
p = getpass.getpass(prompt='What is your password? (You will not see that you are typing because it is a password) ')
subjectss = input('Subject? ')
msginp = input('Body? ')
toaddr = input('To who do you want to send it to? ')
msg = MIMEText(msginp)
msg['Subject'] = subjectss
msg['From'] = usern
msg['To'] = toaddr
s = smtplib.SMTP(smtpserverinp, 587)
s.starttls()
s.login(usern, p)
s.sendmail(usern, toaddr, msg.as_string())
s.quit()
Thanks!
I can't add a comment to see if this was totally what you want but i'll give it ago.
Your msginp = input('Body? ') ends once you press the enter key, for a new line you'd need to enter \n. Rather than typing \n each time you can make a loop.
Once all the data has been collected you can use the MIMEText as you would before.
Replace your msginp and MIMEText with this (total is the msginp)
total = ""
temp = input("Data: ")
total = temp+"\n"
while(temp!=""):
temp = input("next line: ")
total = total+temp+"\n"
msg = MIMEText(total)
Exit when you enter empty line
print("Body? ", end="")
lines = []
while True:
line = input("")
if not len(line):
break
lines.append(line)
print("\n".join(lines))

error sending multiple mails through smtp

I am trying to develop a small python application that allows it's user to send multiple mails through python, I am using gmail, I have allowed Access for less secure apps, it doesn't send.
I have searched stackoverflow for similar problems, but it seemed that most of the used codes are completely different in implementation, even after trying many of hem, they all through exception
import smtplib
from telnetlib import Telnet
def addSenders(message):
num = input("enter number of recievers : ")
num = int (num)
i = 0
emailList = []
while i < num :
nameStr = input("enter name")
mailStr = input("enter e-mail")
emailList.append(mailStr)
if i == 0:
message += nameStr + " <" + mailStr + ">"
print(message)
else:
message += "," + nameStr + " <" + mailStr + ">"
i = i + 1
return emailList, message
sender = 'xxxx#gmail.com'
password = "xxxx"
message = """From: xxxx xxxx <xxxxx#gmail.com>
To: To """
to, message = addSenders(message)
message += """
MIME-Version: 1.0
Content-type: text/html
Subject: Any Subject!
<h1> Good Morning :D <h1>
"""
server = smtplib.SMTP('smtp.gmail.com',587)
server.ehlo()
server.starttls()
server.login(sender, password)
try:
server.sendmail(sender, [to], message)
print ("Successfully sent email")
except:
print ("Error: unable to send email")
server.quit()
output : Error: unable to send email

Printing subjects and sender from email in python

I'm trying to get a python script which looks through my gmail inbox using imap and prints out the subject and sender of any emails which are unseen. I've started but at the moment I don't think it can sort the unseen emails or extract from these the subject and sender.
Does anyone know how to finish this code?
import imaplib
import email
user = "x"
password = "y"
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(user, password)
mail.list()
mail.select('inbox')
unseen_emails = mail.search(None, 'UnSeen')
print unseen_emails
If you were willing to use poplib, this should work.
import poplib
mymail = []
host = "pop.gmail.com"
mail = poplib.POP3_SSL(host)
print (mail.getwelcome())
print (mail.user("user#gmail.com"))
print (mail.pass_("password"))
print (mail.stat())
print (mail.list())
print ("")
if mail.stat()[1] > 0:
print ("You have new mail.")
else:
print ("No new mail.")
print ("")
numMessages = len(mail.list()[1])
numb=0
for i in range(numMessages):
for j in mail.retr(i+1)[1]:
numb+=1
if numb == 4 or numb == 5:
print(j)
mail.quit()
input("Press any key to continue.")
Just be sure to allow less secure apps in your google account here: https://myaccount.google.com/lesssecureapps
My external lib https://github.com/ikvk/imap_tools
from imap_tools import MailBox, AND
# get list of unseen emails from INBOX folder
with MailBox('imap.mail.com').login('test#mail.com', 'pwd', 'INBOX') as mailbox:
for msg in mailbox.fetch(AND(seen=False)):
msg.subject # str: 'some subject 你 привет'
msg.from_ # str: 'Sender#ya.ru'
NOTE: mailbox.fetch has mark_seen arg!

python emailing one line at a time

My email program is emailing each line of the message as a separate email, i would like to know how to send all of the message in one email, when the email is sent the program will return to the beginning.
import smtplib
from email.mime.text import MIMEText
a = 1
while a == 1:
print " "
To = raw_input("To: ")
subject = raw_input("subject: ")
input_list = []
print "message: "
while True:
input_str = raw_input(">")
if input_str == "." and input_list[-1] == "":
break
else:
input_list.append(input_str)
for line in input_list:
# Create a MIME text message and populate its values
msg = MIMEText(line)
msg['Subject'] = subject
msg['From'] = '123#example.com'
msg['To'] = To
server = smtplib.SMTP_SSL('server', 465)
server.ehlo()
server.set_debuglevel(1)
server.ehlo()
server.login('username', 'password')
# Send a properly formatted MIME message, rather than a raw string
server.sendmail('user#example.net', To, msg.as_string())
server.close()
(the part that takes multiple lines was made with the help Paul Griffiths, Multiline user input python)
for line in input_list:
# Create a MIME text message and populate its values
msg = MIMEText(line)
You are calling server.sendmail in this loop.
Build your entire msg first (in a loop), THEN add all of your headers and send your message.

Categories

Resources