Headers on a mime message must be strings. You have assigned a tuple to From, and a list to To.
Make those strings too:
message['From'] = "Michal <{}>".format(FROM)
message['To'] = ', '.join(TOADDR)
Answer from Martijn Pieters on Stack OverflowI am trying to call the function send_email with the variable message in it and combining it with a string contained in AlertSMSText and assigning it to text as well as html to HTMLEmailBody.
For some reason when I do text = AlertSMSText, message and it gives me the error AttributeError: 'tuple' object has no attribute 'encode' but if I do text = AlertSMSText + message and html = HTMLEmailBody + message it works fine except it ignores \n contained in the string that AlertSMSText has in it.
SendEmailAlert.py
def send_email(message):
email_subject = JSONFileReader.SubjectEmail
sender_add = JSONFileReader.SenderEmail
receiver_add = JSONFileReader.ReceiverEmail
smsEmail_add = JSONFileReader.SMSEmailAdd # SMS email
AlertSMSText = JSONFileReader.AlertSMSText #Alert SMS Text message
HTMLEmailBody = JSONFileReader.AlertHTMLEmailBody #Alert Email message in HTML format
password = JSONFileReader.gmailPass # Password for the email you're sending from
# Below is creating the SMTP server object by giving the SMPT server an address and port number
smtp_server = smtplib.SMTP("smtp.gmail.com", 587)
smtp_server.ehlo() # setting the ESMTP protocol
smtp_server.starttls() # setting up to TLS connection
smtp_server.ehlo() # calling the ehlo() again as encryption happens on calling startttls()
smtp_server.login(sender_add, password) # logging into the senders email
rcpt = smsEmail_add.split(",") + [receiver_add] # Formats the recipients emails
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = email_subject
msg['From'] = sender_add
msg['To'] = receiver_add
msg['Cc'] = smsEmail_add
message.encode('utf-8')
# Create the body of the message (a plain-text is for SMS and HTML is for email)
text = AlertSMSText, message
html = HTMLEmailBody, message
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
smtp_server.sendmail(sender_add, rcpt, msg.as_string()) #Sends the email
smtp_server.quit() #Terminates the SMTP server
ip= "10.1.50.2"
send_email(ip + " is down.\n\nPlease reply with 'Ack' to pause alerts for 60 minutes")In the JSON, the AlertSMSTextvariable equals to "Alert SMS Text": "This is an alert for your services \n\n IP: "
The output when text = AlertSMSText + message is all on one line and ignores newline \n:
This is an alert for your services IP:10.1.50.0 is down. Please reply with 'Ack' to pause alerts for 60 minutes
I want it to be:
This is an alert for your services IP:10.1.50.0 is down. Please reply with 'Ack' to pause alerts for 60 minutes
python - How to fix AttributeError: "NoneType" object has no attribute "encode" using smtplib - Stack Overflow
email - Python error: 'tuple' object has no attribute 'encode' - Stack Overflow
python - 'tuple' object has no attribute 'encode' - Stack Overflow
python 3.x - 'SMTP' object has no attribute 'encode' - Stack Overflow
This usually occurs when you create the environment variables but forget to restart your editor. So a simple restart should fix the problem.
You are doing server.login(addr, pw), but getting addr and pw through environment variables. It seems you have not actually passed them like that.
MIMEText takes a string as its first argument. You're creating text1 as a tuple. You need something more like
"First Name: %s\nLast Name: %s" % (first_name, last_name)
you need to attach part1 to msg:
msg.attach(part1)
you can also find a good example of how to send a multipart email message in the Python Documenation
For avoid SQL-injections Django documentation fully recommend use placeholders like that:
import mysql.connector
conn = mysql.connector.connect(host='localhost',user='user1',password='puser1',db='mm')
cursor = conn.cursor()
string1 = 'test1'
insert_query = """INSERT INTO items_basic_info (item_name) VALUES (%s)"""
cursor.execute(insert_query, (string1,))
conn.commit()
You have to pass tuple/list params in execute method as second argument. And all should be fine.
Not exactly OP's problem but i got stuck for a while writing multiple variables to MySQL.
Following on from Jefferson Houp's answer, if adding in multiple strings, you must specify the argument 'multi=True' in the 'cursor.execute' function.
import mysql.connector
conn = mysql.connector.connect(host='localhost',user='user1',password='puser1',db='mm')
cursor = conn.cursor()
string1 = 'test1'
string2 = 'test2'
insert_query = """INSERT INTO items_basic_info (item_name) VALUES (%s, %s)"""
cursor.execute(insert_query, (string1, string2), multi=True)
conn.commit()
I am creating a Contact page for my django project. forms.py has name, subject, sender and message. Here's the view:
And the form:
<form method="POST">
{%csrf_token%}
{{form.as_p}}
<button type="submit">Send</button>
</form>
After I click Send I get this error: AttributeError: 'tuple' object has no attribute 'encode' and I can't seem to figure out what's wrong despite checking other questions of the same type.
I am using google SMTP server, from this link following its instructions.
You should provide the full trace back. We aren't mind readers.
Only thing I can think of is if you have other elements on the HTML form with the same name (”name”, “sender_email”, “subject”, or “message”). That, or try to remove the comma in the recipient list. I don’t think it’s the list, though.
Hi all! So Ive been trying to make a program that sends me an email via python when something happens but I'm having alot of difficulty with the email part...
I have been reading a heap of different things about how to do it and eventually went with [this one] (https://docs.python.org/2.7/library/email-examples.html).
I filled in my code using a free smtp server and it looks like:
def SendEmail():
from email.mime.text import MIMEText
# Open a plain text file for reading. For this example, assume that
# the text file contains only ASCII characters.
fp = open('message.txt', 'r+')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % 'test'
msg['From'] = 'myemaile@gmail.com'
msg['To'] ='myemail@gmail.com'
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('smtp-pulse.com')
s.sendmail(msg['From'], msg['To'], msg.as_string())
s.quit()inserting my actual email, however when I run it I get the following error:
(501, b'Syntactically invalid HELO argument(s)')
Ive googled this and all I can find is errors due to the input host address or something due to them hosting this incorrectly, but I'm not really sure how to fix it...
Any help would be greatly appreciated :D
EDIT: Okay so u/johninbigd kindly pointed out that the 'TO' field has to be a list, I did forget about that and now I'm getting this error:
AttributeError: 'list' object has no attribute 'encode'
Edit: WOOO finally got it working. The issue was just I had to go into google settings and allow less secure apps or something like that. Also removed all that code and followed the instructions from here:
http://www.mkyong.com/python/how-do-send-email-in-python-via-smtplib/