I have the next function:
hostname = os.uname()[1]
def sendmail(sender, receiver, content, user=None, password=None, hostname='localhost', port=25,ssl=False):
smt_server = 'localhost'
port = '25'
sender = 'jenkins#jenkins.com'
receiver = 'test#test.es'
content = "I need to show hostname here" , hostname , "Done."
msg = MIMEText(content)
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = 'Simple app script'
try:
s = smtplib.SMTP('localhost', port )
s.sendmail('jenkins#jenkins.com', 'test#test.es', content)
s.quit()
print "Succesfully sent email"
except SMTPException:
print "Error: fail to send email"
Actual result:
AttributeError: 'tuple' object has no attribute 'encode'
Expected result:
The body message of the mail have to be:
I need to show hostname here MyHostname Done.
I'm not sure if i'm using the rigth way, could you help me?
Thanks
You can add strings:
content = "I need to show hostname here" + hostname + "Done."
Try this to make content one string.
content = "I need to show hostname here " + hostname + " Done."
Related
This code is supposed to send an email to a specified address and when I hard code the "TEXT" & "SUBJECT" it seems to send fine but when I create it as a function and call it it never sends the email and never prints the "Notification Sent" message. What am I missing?
Tried hard coding the TEXT and SUBJECT and it sends fine! NOTE: YOU MUST ENABLE LESS SECURE APPS WHEN USING GMAIL!
import smtplib
class email_thing:
def email_notification(self,SUBJECT,TEXT):
TO = 'email#example.com'
self.SUBJECT = SUBJECT
self.TEXT = TEXT
gmail_sender = 'email#example.com'
gmail_passwd = 'examplepassword'
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(gmail_sender, gmail_passwd)
return self.SUBJECT
return self.TEXT
BODY = '\r\n'.join(['To: %s' % TO,
'From: %s' % gmail_sender,
'Subject: %s' % SUBJECT,
'',TEXT])
try:
server.sendmail(gmail_sender, [TO], BODY)
print ('Notification Sent!')
except:
print ('error sending mail')
server.quit()
test_send = email_thing()
test_send.email_notification(SUBJECT ='Test Email',TEXT = 'This is a test from python!')
Remove
return self.SUBJECT
return self.TEXT
return exits method at once so code after return is never executed.
Code works fine up to writing the 'body' of the DATA command (message content that ends with a line containing nothing but a '.' char).
Socket simply keeps waiting for a .recv() message - no error code returned. If a socket.timeout() option is set, it just prints a 'nothing received' error.
address = "smtp.gmail.com"
port = 465
mailserver = (address, port)
sockplain = socket.socket(socket.AF_INET)
context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
context.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1
sockssl = context.wrap_socket(sockplain, server_hostname=address)
sockssl.connect(mailserver)
def sendToSMTPserver(*vararg):
email_address = "email address goes here"
message_code = "SMTP code goes here e.g. 'RCPT TO'"
mailFrom = "complete message goes here"
if len(vararg) > 1:
message_code, username = vararg
mailFrom = message_code + ":" + username + "\r\n"
else:
message_code = vararg[0]
mailFrom = message_code + "\r\n"
sockssl.send(mailFrom.encode())
print(sockssl.recv(1024))
sendToSMTPserver("EHLO Alice")
sendToSMTPserver("AUTH LOGIN")
sendToSMTPserver(base64.b64encode(username))
sendToSMTPserver(base64.b64encode(password))
sendToSMTPserver("MAIL FROM", "<" + username + ">")
sendToSMTPserver("RCPT TO", "<" + username + ">")
sendToSMTPserver("DATA")
# works fine until here ...
sendToSMTPserver("hangs after sending this line \n.")
The other SMTP server is expecting \r\n for the end of lines, so at the moment you don't have a full stop on its own line, i.e. \r\n.\r\n
So, you need to simply change the last line to
sendToSMTPserver("hangs after sending this line \r\n.")
Adding a extra \r
I am not that experienced with python, but do some python coding for small jobs. Currently I have a job that opens a log file and pulls any records that are considered errors. This list of errors is then added as part of an email notification. What I would like to do is either include the list or a notification that the list was empty. I have been able to do this in the console, but don't know how to get this added as a parameter in the email.
if errorlist:
print "\n".join(errorlist)
else:
print "No Errors Found"
# Send Email
SMTP_SERVER = {SMTP SERVER}
SMTP_PORT = {SMTP PORT}
sender = {Sender}
password = {Password}
recipient = {Recipient}
subject = "This is the subject line"
errorlist = "<br>" "\n".join(errorlist)
body = "" + errorlist + ""
headers = ["From: " + sender,
"Subject: " + subject,
"To: " + ", " .join(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()
The email is sent in this line:
session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
The body variable contains the body of your email. In order to add something into the body of the email, it should be added to the string contained by the body variable. Adapting the code you already have added (which successfully prints your desired result), you could replace this line:
body = "" + errorlist + ""
with this:
if errorlist:
body = "\n".join(errorlist)
else:
body = "No Errors Found"
if errorlist:
error_string = "\n".join(errorlist) # assign it to variable
print (error_string) # still print it
else:
error_string = "" # assign blank to error_string
print ("No Errors Found") # still print "no errors found"
.
.
.
body = ""+error_string+"" # 'body = error_string' is the same though
.
.
.
session.sendmail(sender, recipient, headers + "\r\n\r\n" + body) # this line you could replace "body" with "error_string" because they are pretty much goign to be equivilant because of the previous comment
You want to assign your error string into a variable, and then use the variable later when constructing the body. Also there is more room for simplification
I am very new to this whole Python 3.4 syntax and need some help working out this portion of my SMTP mailer. Anyways, if you could help that would be great! Below is the code in Python script.
print ('SMTP Mailbox Spammer v1')
import smtplib
smtpObj = smptlib.SMTP( [smtp.gmail.com [ 465]] )
receive = str(input('Receiver: '))
subject = str(input('Subject: '))
message = str(input('Message: '))
sender = 'johnappleseed3113#gmail.com'
receivers = ['to#todomain.com']
message = """From: From Person <johnappleseed3113#gmailc.om>
To: To Person <"""receive""">
Subject: """subject"""
"""message"""
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
you should remove tab below.
sender = 'johnappleseed3113#gmail.com'
receivers = ['to#todomain.com']
message = """From: From Person
To: To Person <"""receive""">
Subject: """subject"""
"""message"""
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
I've written a Python script to automatically send some information to my friends. I used SMTPlib, it works well if I only sent to me or one additional email.
When I try to send to 17 emails, (including my sender email), then it shows in sent mail on web-based Gmail. I saw that the mail was sent but I didn't receive it. Only the first recipient received the email.
If I reply to all from that mail, then everyone got only that reply.
I can't figure out why they didn't receive it when I sent it from script, I ask my friend check spam, but she didn't find anything.
This is my code:
#!/usr/bin/env python
import smtplib
import csv
from datetime import datetime, timedelta
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
sender = 'MYBOT#gmail.com'
password = None
with open('pass', 'rt') as f:
password = f.read().strip('\n')
def send_mail(recipient, subject, body):
"""
Send happy bithday mail
"""
headers = ["From: " + sender,
"Subject: " + subject,
"To: " + recipient,
"MIME-Version: 1.0",
"Content-Type: text/html"]
headers = "\r\n".join(headers)
smtp = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
smtp.ehlo()
smtp.starttls()
smtp.ehlo
smtp.login(sender, password)
body = "" + body +""
smtp.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
print "Sent to ",
print recipient
smtp.quit()
def send_happybirthday(recipient):
body = """Happy birthday to you!
\n<br/>From C2k8pro with love
"""
subject ='[BirthReminder] Happy birthday to you! from C2k8pro'
send_mail(recipient, subject, body)
def send_notification(all_mails, names):
body = """Tomorrow is birthday of %s""" % names
send_mail(all_mails, body, body)
def test_send_mail():
notify_body = """Tomorrow is birthday of """
recipients = ['MYBOT#gmail.com']
today = datetime.now()
format = "%d-%m-%Y"
print today
today_in_str = datetime.strftime(today, format)
def read_csv():
FILENAME = 'mails.csv'
reader = csv.reader(open(FILENAME, 'rt'), delimiter=',')
today = datetime.now()
one_day = timedelta(days=1)
tomorrow = today + one_day
all_mails = []
str_format = "%d/%m"
str_today = today.strftime(str_format)
str_tomorrow = tomorrow.strftime(str_format)
print 'Today is ', str_today
tomorrow_birth = []
for row in reader:
name = row[1].strip()
dob = row[2]
dmy = dob.split("/")
mail = row[3]
all_mails.append(mail)
#TODO fix dob with only 1 digit
birth_date = dmy[0] + "/" + dmy[1]
if str_today == birth_date:
print 'Happy birthday %s' % name
try:
send_happybirthday(mail)
except Exception, e:
print e
elif str_tomorrow == birth_date:
tomorrow_birth.append(name)
print "Tomorrow is %s's birthday" % name
# Remove empty string
all_mails = filter(None, all_mails)
print 'All mails: ', len(all_mails)
str_all_mails = ', '.join(all_mails)
if tomorrow_birth:
all_tomorrow = ', '.join(tomorrow_birth)
send_notification(str_all_mails, all_tomorrow)
def main():
read_csv()
if __name__ == "__main__":
main()
Can anyone explain this. Thanks!
I found solution from here
Send Email to multiple recipients from .txt file with Python smtplib
I passed a string contain all recipients separated by comma to msg['To'] and sendmail().
It's true for msg['To'] but with sendmail, I have to use a list.