def mail():
server = smtplib.SMTP('smtp-mail.outlook.com',587)
server.starttls()
server.login(env, password)
server.sendmail(env,rec,msg =str(list))
print("Login no servidor efetuado com Sucesso")
print("Email enviado para " + rec)
server.close()
I use this code to send an email but the email comes empty i tryed to swap msg = str(list) to just list tried remove message and type in the third argument just a string and emails always come empty
server.sendmail(env,rec,msg =str(list))
You see what your message contains?
str(list)
Try typing this same thing in a scope in which list is not overwritten (because list is not reassigned in your mail function).
>>> str(list)
"<class 'list'>"
For sure that's not the right way of doing this.
What's more, in the same line of code above I don't see the assignation of env and rec, so I guess there must be some error there.
Related
I am experimenting with smtplib in Python3.
I want to send the content of a variable to an email address. If there is an smtplib.SMTPAuthenticationError, I want to send that variable to an alternative email address. This works (see code below). But what if I want to add a third email address (if the first two fail for some reason)?
I don't think try and except allow me to add another block of the same code (with different email login details).
I know with subprocess, it's possible to acquire the returncode of a variable and then use if.
For example:
result = subprocess.run(["ls", "-al"], capture_output = True)
if result !=0:
do_something_to_list_the_directory
I don't know how this can be done without using subprocess. Can anyone please advise?
Code below:
try:
mail_sending_attempt = smtplib.SMTP("smtp_provider", 587)
mail_sending_attempt.starttls()
mail_sending_attempt.login(send, passinfo) ### this will not work
mail_sending_attempt.sendmail(send, receive, message)
mail_sending_attempt.quit()
except Exception:
mail_sending_attempt = smtplib.SMTP("smtp_provider", 587)
mail_sending_attempt.starttls()
mail_sending_attempt.login(send2, passinfo2) ### this will not work
mail_sending_attempt.sendmail(send2, receive2, message)
mail_sending_attempt.quit()
In case there are more email, you can use following snippet
from dataclasses import dataclass
#dataclass
class EmailData:
send: str
passinfo: str
receive: str
main = EmailData("send1", "passinfo1", "receive1")
backup_1 = EmailData("send2", "passinfo2", "receive2")
...
for data in [main, backup_1, ...]:
try:
mail_sending_attempt = smtplib.SMTP("smtp_provider", 587)
mail_sending_attempt.starttls()
mail_sending_attempt.login(data.send, data.passinfo)
mail_sending_attempt.sendmail(data.send, data.receive, message)
mail_sending_attempt.quit()
break
except Exception:
continue
else:
# the case when we won't encounter break, so every login failed.
raise Exception
I have a script that emails me links to me.
The problem is the links arent included, instead I get:
<function <lambda> at 0x7f75b5fb4a60>
My script looks like:
from bs4 import BeautifulSoup
import re
import requests
ex_webdev_js_by_city = [
'http://boston.website.org/search/web',
]
ex_web_j_keywords = [['one'],['coool', 'person']]
ex_web_j_keywords = sum(ex_web_j_keywords, [])
ex_js = []
for webdev_j_for_a_city in ex_webdev_js_by_city:
webdev_j = requests.get(webdev_j_for_a_city)
soup = BeautifulSoup(webdev_j.text, "lxml")
for j_keyword in ex_web_j_keywords:
for a in soup.find_all('a', class_="result-title hdrlnk", text=re.compile(j_keyword,re.IGNORECASE)):
#print(a.get('href'))
ex_js.append(a.get('href'))
if ex_js:
#email them to myself!
import smtplib, socket
TO = 'myemail#gmail.com'
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
TEXT = lambda: print(('Latest js from site:\n\n{}'*len(ex_js)).format(*ex_js))
#Gmail Sign In
gmail_sender = 'myemail'
gmail_passwd = 'mypass'
server.login(gmail_sender, gmail_passwd)
msg = str(TEXT)
server.sendmail(gmail_sender, gmail_sender, msg)
print('Sent you some links!')
server.quit()
except socket.error as e:
print ('error sending mail, error was {}'.format(e))
The error is occuring on this line (I believe):
lambda: print(('Latest js from site:\n\n{}'*len(ex_js)).format(*ex_js))
It appears its printing out the object details in the email to me, and not the value.
Thus, what am i possibly doing wrong here?
I don't know why you use print or lambda anyway. If you simply wrote:
msg = ('Latest js from site:\n\n{}'*len(ex_js)).format(*ex_js)
and drop the:
msg = str(TEXT)
it should probably work.
So the try block should read:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
msg = ('Latest js from site:\n\n{}'*len(ex_js)).format(*ex_js)
#Gmail Sign In
gmail_sender = 'myemail'
gmail_passwd = 'mypass'
server.login(gmail_sender, gmail_passwd)
# msg = str(TEXT) !!commented out!! (only to make it explicit)
server.sendmail(gmail_sender, gmail_sender, msg)
print('Sent you some links!')
server.quit()
I think however that you do not really understand what lambda and print are supposed to do. print is used to write data to the standard output channel, but you want to write it into an email, so you do not need to print it locally, you need somehow to store your message in memory.
Finally lambda:... is used to create an anonymous function, if you do not feed it any arguments, its usage is usually to postpone execution (for instance to achieve laziness). But here you actually need the message, so again no need to use this construct.
When you say
TEXT = lambda: print(('Latest js from site:\n\n{}'*len(ex_js)).format(*ex_js))
Yo are simply creating lambda function , it is not executed yet . In order to execute you need to specifically invoke it by calling TEXT()
In order to fix your problem change to
TEXT = lambda: ('Latest js from site:\n\n{}'*len(ex_js)).format(*ex_js)
And msg = str(TEXT())
I've searched a fair bit on this and couldn't come up with anything satisfactory.
I've been trying to write a python program to listen for email bounce reports and depending on the reason for the bounce resend them at different intervals.
import smtplib
from smtplib import *
sender = 'foo#bar.com'
receivers = ['42#life.com']
message = """From: From Arthur <foo#bar.com>
To: To Deep Thought <42#life.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP('smtp.gmail.com',587)
smtpObj.starttls()
smtpObj.login(sender,'foo#bar.com')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPResponseException:
error_code = SMTPResponseException.smtp_code
error_message = SMTPResponseException.smtp_error
print "Error code:"+error_code
print "Message:"+error_message
if (error_code==422):
print "Recipient Mailbox Full"
elif(error_code==431):
print "Server out of space"
elif(error_code==447):
print "Timeout. Try reducing number of recipients"
elif(error_code==510 or error_code==511):
print "One of the addresses in your TO, CC or BBC line doesn't exist. Check again your recipients' accounts and correct any possible misspelling."
elif(error_code==512):
print "Check again all your recipients' addresses: there will likely be an error in a domain name (like mail#domain.coom instead of mail#domain.com)"
elif(error_code==541 or error_code==554):
print "Your message has been detected and labeled as spam. You must ask the recipient to whitelist you"
elif(error_code==550):
print "Though it can be returned also by the recipient's firewall (or when the incoming server is down), the great majority of errors 550 simply tell that the recipient email address doesn't exist. You should contact the recipient otherwise and get the right address."
elif(error_code==553):
print "Check all the addresses in the TO, CC and BCC field. There should be an error or a misspelling somewhere."
else:
print error_code+": "+error_message
To which I get the following error:
Traceback (most recent call last): File "C:/Users/Varun
Shijo/PycharmProjects/EmailBounce/EmailBounceTest.py", line 20, in
error_code = SMTPResponseException.smtp_code AttributeError: type object 'SMTPResponseException' has no attribute 'smtp_code'
I read somewhere that I should be trying to get the attribute from an instance of the SMTPResponseException class (even though the smtplib documentation says otheriwse) so I tried that too, but I wasn't sure of what arguments to pass its constructor (code,msg).
Could someone please nudge me in the right direction?
Thanks.
try with
except SMTPResponseException as e:
error_code = e.smtp_code
error_message = e.smtp_error
I'm trying to send a text message over Tkinter. So you input sms:hello. That sends a text message that says hello. To do this it emails the word using the AT&T email server and GMail. So the program reads INFO.txt which contains all the email authentications g_user g_pass and m_num. Then it uses those to send an email which sends the text message.
Now my problem is that UnboundLocalError: local variable 'g_user' referenced before assignment. Which I know is caused by something not being a global variable. Can anyone help me out? I'm stumped...
root = Tk()
#open file
file=open('INFO.txt')
line=file.readline()
if 'Mobile_number:::' in line:
m_num=line[16:]
if 'GMail_name:::' in line:
g_user=line[13:]
if 'GMail_pass:::' in line:
g_pass=line[13:]
def callback(event):
text = inputfield.get()
if 'sms:' in text:
textmessage()
def textmessage():#sms:
import smtplib
#open file
file=open('INFO.txt')
line=file.readline()
if 'Mobile_number:::' in line:
m_num=line[16:]
if 'GMail_name:::' in line:
g_user=line[13:]
if 'GMail_pass:::' in line:
g_pass=line[13:]
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
sender = '{}#gmail.com'.format(g_user)
password='{}'.format(g_pass)
recipient = '{}#txt.att.net'.format(m_num)
subject = 'Gmail SMTP Test'
body = text[4:]
"Sends an e-mail to the specified recipient."
body = "" + body + ""
headers = ["From: " + sender,
"Subject: " + subject,
"To: " + recipient,
"MIME-Version: 1.0",
"Content-Type: text/html"]
headers = "\r\n".join(headers)
session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
session.ehlo()
session.starttls()
session.ehlo
session.login(sender, password)
session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
session.quit()
text2=text[4:]
confirmation="SMS containing '{}' sent".format(text2)
tex.insert(END,confirmation)
tex=Text(root)
tex.pack(side='right')
inputfield = Entry(root)
inputfield.pack(side='bottom')
inputfield.bind('<Return>', callback)
root.mainloop()
The problem is most likely with this line:
sender = '{}#gmail.com'.format(g_user)
because the if statement condition (if 'GMail_name:::' in line) is evaluating to False and then your g_user variable is never defined in the local scope of that function.
Take a close look at the error message:
UnboundLocalError: local variable 'g_user' referenced before assignment
A pretty good rule of thumb is to assume that the error message is telling the truth. In this case it is telling you two very important details:
It thinks g_user is a local variable
It thinks g_user was used before it was set
To solve this, you need to answer why to one or both of those questions. Why does it think it is local, and/or why does it think it wasn't set? If you mentally step through the code, you'll probably answer one or both of those questions.
For example, ask youself the question "how does g_user" get set if 'GMail_name:::' in line returns false? Have you verified that the if statement is true? Is your code prepared to handle the case where it's false? Have you literally proven to yourself that the if statement is true, or are you just assuming it's true?
Also, answer this question: are you reading every line from INFO.txt, or are you reading a single line? If you're only reading a single line, is that intentional? It looks like you are expecting both the username and password to be at position [13:] in the line, which will be impossible if both values are different and both values are on the same line.
Since you are just now learning to program, don't just throw lines of code into a file and hope they work, and don't get others to solve your problems. think about what the computer is doing. Step through the code logically and the problems will become self-evident.
I have a python script that has to fetch unseen messages, process it, and mark as seen (or read)
I do this after login in:
typ, data = self.server.imap_server.search(None, '(UNSEEN)')
for num in data[0].split():
print "Mensage " + str(num) + " mark"
self.server.imap_server.store(num, '+FLAGS', '(SEEN)')
The first problem is that, the search returns ALL messages, and not only the UNSEEN.
The second problem is that messages are not marked as SEEN.
Can anybody give me a hand with this?
Thanks!
import imaplib
obj = imaplib.IMAP4_SSL('imap.gmail.com', '993')
obj.login('user', 'password')
obj.select('Inbox') <--- it will select inbox
typ ,data = obj.search(None,'UnSeen')
obj.store(data[0].replace(' ',','),'+FLAGS','\Seen')
I think the flag names need to start with a backslash, eg: \SEEN
I am not so familiar with the imaplib but I implement this well with the imapclient module
import imapclient,pyzmail,html2text
from backports import ssl
context=ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
iobj=imapclient.IMAPClient('outlook.office365.com', ssl=True, ssl_context=context)
iobj.login(uname,pwd)# provide your username and password
iobj.select_folder('INBOX',readonly=True)# Selecting Inbox.
unread=iobj.search('UNSEEN')# Selecting Unread messages, you can add more search criteria here to suit your purpose.'FROM', 'SINCE' etc.
print('There are: ',len(unread),' UNREAD emails')
for i in unread:
mail=iobj.fetch(i,['BODY[]'])#I'm fetching the body of the email here.
mcontent=pyzmail.PyzMessage.factory(mail[i][b'BODY[]'])#This returns the email content in HTML format
subject=mcontent.get_subject()# You might not need this
receiver_name,receiver_email=mcontent.get_address('from')
mail_body=html2text.html2text(mcontent.html_part.get_payload().decode(mcontent.html_part.charset))# This returns the email content as text that you can easily relate with.
Let's say I want to just go through the unread emails, reply the sender and mark the email as read. I'd call the smtp function from here to compose and send a reply.
import smtplib
smtpobj=smtplib.SMTP('smtp.office365.com',587)
smtpobj.starttls()
smtpobj.login(uname,pwd)# Your username and password goes here.
sub='Subject: '+str(subject)+'\n\n'# Subject of your reply
msg='Thanks for your email! You're qualified for the next round' #Some random reply :(
fullmsg=sub+new_result
smtpobj.sendmail(uname,test,fullmsg)# This sends the email.
iobj.set_flags(i,['\\Seen','\\Answered'])# This marks the email as read and adds the answered flag
iobj.append('Sent Items', fullmsg)# This puts a copy of your reply in your Sent Items.
iobj.logout()
smtpobj.logout()
I hope this helps