I have a program written in python 2.7, which sends a photo attached to an email. So far I have not had any problems but because I use it and other things in my program I have to upgrade it to python 3 and I encounter the following problems:
def sendEmail(self, q, Subject, textBody, attachment, receiver):
"""This method sends an email"""
EMAIL_SUBJECT = Subject
EMAIL_USERNAME = 'sistimaasfalias#gmail.com' #Email address.
EMAIL_FROM = 'Home Security System'
EMAIL_RECEIVER = receiver
GMAIL_SMTP = "smtp.gmail.com"
GMAIL_SMTP_PORT = 587
GMAIL_PASS = 'HomeSecurity93' #Email password.
TEXT_SUBTYPE = "plain"
#Create the email:
msg = MIMEMultipart()
msg["Subject"] = EMAIL_SUBJECT
msg["From"] = EMAIL_FROM
msg["To"] = EMAIL_RECEIVER
body = MIMEMultipart('alternative')
body.attach(MIMEText(textBody, TEXT_SUBTYPE ))
#Attach the message:
msg.attach(body)
msgImage = MIMEImage(file.read())
#Attach a picture:
if attachment != "NO":
msg.attach(MIMEImage(file(attachment).read()))
ERROR MESSAGE:
Process Process-2:2:
Traceback (most recent call last):
File "/usr/lib/python3.7/multiprocessing/process.py", line 297, in _bootstrap
self.run()
File "/usr/lib/python3.7/multiprocessing/process.py", line 99, in run
self._target(*self._args, **self._kwargs)
File "/home/pi/homesecurity/functions.py", line 233, in sendEmail
msgImage = MIMEImage(file.read())
NameError: name 'file' is not defined
The error is correct. You haven't defined file. In Python 2, file was a built-in type, but that no longer exists. The msgImage=MIMEImage(file.read()) would never have made sense, but you aren't using that variable anyway. Delete that line.
Change
msg.attach(MIMEImage(file(attachment).read()))
to
msg.attach(MIMEImage(open(attachment,'rb').read()))
Related
This is my code.
import smtplib
from email.message import EmailMessage
def sendemail(to, subject, message):
msg = EmailMessage()
msg.set_content(message)
msg["subject"] = subject
msg["to"] = to
user = "jibraanahmed234#gmail.com"
msg["from"] = user
password = "pmamhmifmwogjbev"
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(user, password)
server.send_message("jibraanahmed234#gmail.com", "jibraanahmed10#gmail.com", msg)
server.quit()
if __name__ == '__main__':
sendemail("jibraanahmed10#gmail.com", "Hello!", "Hi Jibraan!")
This is the error it returns.
Traceback (most recent call last):
File "/Users/jibraanahmed/code/Python/messaging/sendemail.py", line 23, in <module>
sendemail("jibraanahmed10#gmail.com", "Hello!", "Hi Jibraan!")
File "/Users/jibraanahmed/code/Python/messaging/sendemail.py", line 17, in sendemail
server.send_message("jibraanahmed234#gmail.com", "jibraanahmed10#gmail.com", msg)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/smtplib.py",
line 939, in send_message
resent = msg.get_all('Resent-Date')
AttributeError: 'str' object has no attribute 'get_all'
These are all fake passwords and emails.
I have tried a lot of tutorials that look like they work for most people, what am I doing wrong?
Maybe you should try sendmail instead of send_message.
From the docs:
The arguments have the same meaning as for sendmail(), except that msg is a Message object
I can not remove email from Sent folder. From Inbox folder it removes well. I tried with Sent and with [Gmail]/Sent parameters but it doesn't work. Where it could be the issue?
import imaplib
email = "my#gmail.com"
passw = "mypass"
imapserver = "imap.gmail.com"
def deleteEmailIMAP(user, password, IMAP):
mail = imaplib.IMAP4_SSL(IMAP)
mail.login(user, password)
mail.select("[Gmail]/Sent")
typ, data = mail.search(None, 'subject 2f0802e2-e396-4a37-aeae-3a51b6ad288f')
for num in data[0].split():
mail.store(num, '+FLAGS', r'(\Deleted)')
mail.expunge()
mail.close()
mail.logout()
deleteEmailIMAP(email, passw, imapserver)
logs:
Traceback (most recent call last):
File "/Users/nikolai/Documents/Python/gmail/test/cv.py", line 23, in <module>
deleteEmailIMAP(email, passw, imapserver)
File "/Users/nikolai/Documents/Python/gmail/test/cv.py", line 15, in deleteEmailIMAP
typ, data = mail.search(None, 'subject 2f0802e2-e396-4a37-aeae-3a51b6ad288f')
File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/imaplib.py", line 723, in search
typ, dat = self._simple_command(name, *criteria)
File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/imaplib.py", line 1196, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/imaplib.py", line 944, in _command
', '.join(Commands[name])))
imaplib.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED
The code does not handle errors. That's why it does not catch server's tagged NO response to the SELECT command. It is not visible in the error log, either, but the exception that you've reported means that by the time the code issues SEARCH, no mailbox is opened -- and that means that SELECT must have failed. (Check the IMAP protocol states.)
GMail uses localized mailbox names, so the likely culprit is that the user you're authenticating as does not have a mailbox named [Gmail]/Sent. If you need to discover the "sent folder" mailbox name, try RFC 6154 (or see Google's docs).
So I have this Python send-email file that sends an email (the text from a file) to a recipient specified inside the code:
import smtplib
from email.mime.text import MIMEText
msgContent = open(Sourcefilelocation, "rb")
msg = MIMEText(spam.read())
msgContent.close()
msg['Subject'] = SUBJECT
msg['From'] = FROM_CLIENT_EMAIL
msg['To'] = TO_CLIENT_EMAIL
#THE ERROR BELOW
s = smtplib.SMTP('localhost')
I understand that there is no mail server on localhost, but how do I make a mail server on that and if I can't then why does s = smtplib.SMTP('gmail.com') take so long if it even works? What do I need to make it work? Any help is appreciated.
output: >> Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
s = smtplib.SMTP('gmail.com')
File "C:\Python25\lib\smtplib.py", line 244, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python25\lib\smtplib.py", line 310, in connect
raise socket.error, msg
error: (10013, 'Permission denied')
And the gmail smtp code takes too long.
I'm running pyramid on an Ubuntu Linux server, and am getting a ValueError when trying to use pyramid_mailer. My code is relatively simple, anything seems to cause it:
def my_view(request):
mailer = get_mailer(request)
emailMessage = Message(subject="Welcome", sender="noreply#mysite.com", recipients = ["me#email.com"], body="test")
mailer.send(emailMessage)
Results in this error:
Traceback (most recent call last):
File "/usr/share/nginx/wwwProj/local/lib/python2.7/site-packages/pyramid-1.5-py2.7.egg/pyramid/router.py", line 242, in __call__
response = self.invoke_subrequest(request, use_tweens=True)
File "/usr/share/nginx/wwwProj/local/lib/python2.7/site-packages/pyramid-1.5-py2.7.egg/pyramid/router.py", line 217, in invoke_subrequest
response = handle_request(request)
File "/usr/share/nginx/wwwProj/local/lib/python2.7/site-packages/pyramid_debugtoolbar-2.0.2-py2.7.egg/pyramid_debugtoolbar/toolbar.py", line 160, in toolbar_tween
return handler(request)
File "/usr/share/nginx/wwwProj/local/lib/python2.7/site-packages/pyramid-1.5-py2.7.egg/pyramid/tweens.py", line 21, in excview_tween
response = handler(request)
File "/usr/share/nginx/wwwProj/local/lib/python2.7/site-packages/pyramid_tm-0.7-py2.7.egg/pyramid_tm/__init__.py", line 79, in tm_tween
manager.abort()
File "/usr/share/nginx/wwwProj/local/lib/python2.7/site-packages/transaction-1.4.3-py2.7.egg/transaction/_manager.py", line 116, in abort
return self.get().abort()
File "/usr/share/nginx/wwwProj/local/lib/python2.7/site-packages/transaction-1.4.3-py2.7.egg/transaction/_transaction.py", line 468, in abort
reraise(t, v, tb)
File "/usr/share/nginx/wwwProj/local/lib/python2.7/site-packages/transaction-1.4.3-py2.7.egg/transaction/_transaction.py", line 453, in abort
rm.abort(self)
File "/usr/share/nginx/wwwProj/local/lib/python2.7/site-packages/repoze.sendmail-4.2-py2.7.egg/repoze/sendmail/delivery.py", line 119, in abort
raise ValueError("TPC in progress")
ValueError: TPC in progress
I followed the instructions for "Getting Started (The Easier Way)" on this site: http://pyramid-mailer.readthedocs.org/en/latest/
This is a known issue. It can be worked around in the meantime by reverting to repoze.sendmail 4.1 (from 4.2)
recipients = ["me#email.com"]
here you can see
recipients – list of email addresses
This was the first error that I encountered while trying to set up an emailing system, through I cannot remember what I did. In any case, I finally got it working for a gmail sender for SMTP. Hope this someone else in my position:
import smtplib
sender = "noreply"
to = "username"
subject = "Verification Code"
headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (sender, to,
subject)
sEmailMessage = headers + "whatever message you want"
mailserver = smtplib.SMTP("smtp.gmail.com", 587)
#--- because of gmail
mailserver.ehlo()
mailserver.starttls()
mailserver.ehlo()
#---
mailserver.login("your_email_address#gmail.com", "your_password")
mailserver.sendmail("from_here#gmail.com", to_here#whatever.com, sEmailMessage)
mailserver.close()
I'm struggling to figure out what went wrong with the below code.
I'm trying to send html mail.
NOW = datetime.datetime.now()
def sendEmail(msg):
global NOW
global SENDER
global EMAILTARGET
today = "%s/%s/%s" % (NOW.month,NOW.day,NOW.year)
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "SAR Data Report - %s" % today
msg['From'] = SENDER
msg['To'] = EMAILTARGET
chunk = MIMEText(msg, 'html')
msg.attach(chunk)
s = smtplib.SMTP('localhost')
s.sendmail(SENDER, EMAILTARGET, msg.as_string())
s.quit()
the above code gives me the following error:
Traceback (most recent call last):
File "./html_mail.py", line 295, in <module>
sendEmail(html)
File "./html_mail.py", line 245, in sendEmail
chunk = MIMEText(msg, 'html')
File "/usr/lib/python2.7/email/mime/text.py", line 30, in __init__
self.set_payload(_text, _charset)
File "/usr/lib/python2.7/email/message.py", line 226, in set_payload
self.set_charset(charset)
File "/usr/lib/python2.7/email/message.py", line 268, in set_charset
cte(self)
File "/usr/lib/python2.7/email/encoders.py", line 73, in encode_7or8bit
orig.encode('ascii')
AttributeError: MIMEMultipart instance has no attribute 'encode'
The error in your code is that you've used msg as an in-parameter to your function and it collides with your MIME message container (both named msg).
What you need to do is to change the name of the in-parameter to something else, like html:
def sendEmail(html):
...
chunk = MIMEText(html, 'html')
...
You're passing msg, which is a MIMEMultipart object, to the MIMEText initializer, which expects a string. You should be passing a string containing the HTML you want to attach, not the message you're trying to attach it to.