python html mail failure - python

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.

Related

I am trying to send an email using python 3.9 using smptlib, why does this not work?

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

Problem in python3 msg.attach(MIMEImage(file(attachment).read()))

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()))

Python SMTP error: "(10013, 'Permission denied')"

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.

Using pyramid_mailer results in ValueError: TPC in progress

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()

Program which send email via Python exits with "AttributeError: 'str' object has no attribute 'get_content_maintype''"

I have python code intended to send an email with an attachment, and I've come down to this:
#!/usr/bin/python
import os, re
import sys
import smtplib
#from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.MIMEText import MIMEText
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
sender = 'me#gmail.com'
password = "e45dt4iamkiddingthisisnotmypassword"
recipient = 'he#gmail.com'
subject = 'Python emaillib Test'
message = 'Images attached.'
def main():
msg = MIMEMultipart()
msg['Subject'] = 'Python emaillib Test'
msg['To'] = recipient
msg['From'] = sender
msg.attach('/tmp/images/a.gif')
part = MIMEText('text', "plain")
part.set_payload(message)
msg.attach(part)
session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
session.ehlo()
session.starttls()
session.ehlo
session.login(sender, password)
# my_message=msg.as_string()
qwertyuiop=msg
session.sendmail(sender, recipient, qwertyuiop.as_string())
session.quit()
if __name__ == '__main__':
main()
And I get this error when running:
Traceback (most recent call last):
File "./abcd.py", line 49, in <module>
main()
File "./abcd.py", line 44, in main
session.sendmail(sender, recipient, qwertyuiop.as_string())
File "/usr/lib/python2.7/email/message.py", line 137, in as_string
g.flatten(self, unixfrom=unixfrom)
File "/usr/lib/python2.7/email/generator.py", line 83, in flatten
self._write(msg)
File "/usr/lib/python2.7/email/generator.py", line 108, in _write
self._dispatch(msg)
File "/usr/lib/python2.7/email/generator.py", line 134, in _dispatch
meth(msg)
File "/usr/lib/python2.7/email/generator.py", line 203, in _handle_multipart
g.flatten(part, unixfrom=False)
File "/usr/lib/python2.7/email/generator.py", line 83, in flatten
self._write(msg)
File "/usr/lib/python2.7/email/generator.py", line 108, in _write
self._dispatch(msg)
File "/usr/lib/python2.7/email/generator.py", line 125, in _dispatch
main = msg.get_content_maintype()
AttributeError: 'str' object has no attribute 'get_content_maintype'
I assume that it has to do with msg.attach("/tmp/images/a.gif") but I'm not sure. The source of the problem is qwertyuiop.as_string() though.
The problem is that msg.attach() attaches another message, not a string/filename. You need to create a MIMEImage object and attach that:
# instead of msg.attach('/tmp/images/a.gif')...
fp = open('/tmp/images/a.gif', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msg.attach(msgImage)
Example adapted from here
If you want types other than Images, check out http://docs.python.org/library/email.mime.html.
The reason you're getting the error on the qwertyuiop.as_string() line is that the message isn't parsed until you call as_string().

Categories

Resources