I have been trying to make the content or message body to appear in the emails but it doesn't appear to be working. It's mentioned that a empty line is needed before the message and with new line after subject. Also, each time I run the script it runs but gives this error "Task timed out after 3.01 seconds" but I get the email, however, the Lambda function is marked as Failed...not sure why?? Maybe that's not so much of a big deal but if it ran then I'm assuming it was successful which is confusing since it says failed. The biggest thing here is the content not showing up. Thank you for any assistance.
import smtplib
sender = 'example.org'
recipient = contact
try:
subject = str(instance_name) + ' Issues'
content="Hello World"
mail = smtplib.SMTP('smtp.office365.com', 587)
mail.ehlo()
mail.starttls()
mail.login('example.org','1234567890')
header = 'To:' + recipient + '\n' + 'From:' \
+sender+'\n'+'subject:' + subject + '\n'
content=header+content
mail.sendmail(sender, recipient, content)
except:
print ("Error: unable to send email")
This works perfectly for me, I hope it will help you out.
import os
import socket
import smtplib
from email.message import EmailMessage
from email.message import EmailMessage
message = EmailMessage()
# Recepients addresses in a list
message['To']=["recepient1#gmail.com","recepient2#gmail.com"]
message['Cc'] = ["cc_recepient#gmail.com"]
message['Bcc'] = ["bcc_recepient#gmail.com"]
message['From'] = "sender#gmail.com"
message['Subject'] = "Subject Matter"
message.set_content("I received the data you sent.")
# Attach a document.
with open("document.txt", "rb") as file:
message.add_attachment(file.read(), maintype="application", subtype="octet-stream",
filename=os.path.basename(file.name))
print(f'Document: {os.path.basename(file.name)} attached successfully.')
# Login in and send your email.
try:
with smtplib.SMTP_SSL("smtp.office365.com", 587) as smtp:
smtp.login('sender#gmail.com', 'password')
print('Sending email...')
smtp.send_message(message)
print(f'Email successfully sent.')
smtp.quit()
except (smtplib.SMTPRecipientsRefused, socket.gaierror):
print ("Error: unable to send email")
I changed this line of code "+sender+'\n'+'subject:' + subject + '\n\n' " and it appears to be working. As far as the timeout issue. I increased it to a minute and it works fine now.
Related
I am trying to send an email using MIME in python. Below is the code I am using :
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
try:
raw_data = request.get_json()
pwd_email_id = raw_data['email']
log.error("Sending email to {}".format(pwd_email_id))
recipients = pwd_email_id
msg = MIMEMultipart()
msg['Subject'] = 'App Registered'
msg['From'] = 'xyz#gmail.com'
msg['To'] = email
message_text = "Dear " + pwd_email_id + "\r\n\r\nYour app has been registered successfully.\r\nBelow are the " \
"details:\r\n\r\n\r\n1.App Name: " + "app_name" + "\r\n2.App Key: " + "app_key" + "\r\n3.Registered Date: " + "registered_date" + "\r\n4.Expiry Date: " + "expiry_date" + "\r\n\r\n\r\nUse app name and app key as headers to make calls to services. " \
"Do not share your app key with anyone.\r\nLet us know if you face any issues.\r\n\r\nThanks "
text = MIMEText(message_text)
msg.attach(text)
s = smtplib.SMTP('smtp.gmail.com', 587)
s.ehlo()
s.starttls()
s.ehlo()
s.login('xyz#gmail.com', '<password>')
s.sendmail("xyz#gmail.com", recipients, msg.as_string())
s.quit()
except Exception as e:
log.error("Exception in sending email {}".format(e))
but its giving me the below error:
module email has no attribute encode
at line:
s.sendmail("xyz#gmail.com", recipients, msg.as_bytes())
I am not able to understand why its giving this error. I have tried only using msg instead of msg.as_bytes() but its still the same. Can anyone please point out the issue in the code. Thanks
Looks like a typo to me.
You have assigned the module email when calling msg['To'] = email. That module must have been imported outside of the shared code (check your imports, it's probably there!). msg.as_string() is simply having trouble parsing the module object (since modules don't have the encode attribute).
I just had the same problem. This error is because input in msg['To'] is the variable email, but you didn't create this variable.
OBS: var email needs to have the email of the person you want to send the msg to. This way, it will be possible to send the message from yours to someone's email.
I have written a script that writes a message to a text file and also sends it as an email.
Everything goes well, except the email finally appears to be all in one line.
I add line breaks by \n and it works for the text file but not for the email.
Do you know what could be the possible reason?
Here's my code:
import smtplib, sys
import traceback
def send_error(sender, recipient, headers, body):
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
session = smtplib.SMTP('smtp.gmail.com', 587)
session.ehlo()
session.starttls()
session.ehlo
session.login(sender, 'my password')
send_it = session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
session.quit()
return send_it
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
sender = 'sender_id#gmail.com'
recipient = 'recipient_id#yahoo.com'
subject = 'report'
body = "Dear Student, \n Please send your report\n Thank you for your attention"
open('student.txt', 'w').write(body)
headers = ["From: " + sender,
"Subject: " + subject,
"To: " + recipient,
"MIME-Version: 1.0",
"Content-Type: text/html"]
headers = "\r\n".join(headers)
send_error(sender, recipient, headers, body)
Unfortunately for us all, not every type of program or application uses the same standardization that python does.
Looking at your question i notice your header is: "Content-Type: text/html"
Which means you need to use HTML style tags for your new-lines, these are called line-breaks. <br>
Your text should be:
"Dear Student, <br> Please send your report<br> Thank you for your attention"
If you would rather use character type new-lines, you must change the header to read: "Content-Type: text/plain"
You would still have to change the new-line character from a single \n to the double \r\n which is used in email.
Your text would be:
"Dear Student, \r\n Please send your report\r\n Thank you for your attention"
You have your message body declared to have HTML content ("Content-Type: text/html"). The HTML code for line break is <br>. You should either change your content type to text/plain or use the HTML markup for line breaks instead of plain \n as the latter gets ignored when rendering a HTML document.
As a side note, also have a look at the email package. There are some classes that can simplify the definition of E-Mail messages for you (with examples).
For example you could try (untested):
import smtplib
from email.mime.text import MIMEText
# define content
recipients = ["recipient_id#yahoo.com"]
sender = "sender_id#gmail.com"
subject = "report reminder"
body = """
Dear Student,
Please send your report
Thank you for your attention
"""
# make up message
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = ", ".join(recipients)
# sending
session = smtplib.SMTP('smtp.gmail.com', 587)
session.starttls()
session.login(sender, 'my password')
send_it = session.sendmail(sender, recipients, msg.as_string())
session.quit()
In my case '\r\n' didn't work, but '\r\r\n' did. So my code was:
from email.mime.text import MIMEText
body = 'Dear Student,\r\r\nPlease send your report\r\r\nThank you for your attention'
msg.attach(MIMEText(body, 'plain'))
The message is written in multiple lines and is displayed correctly in Outlook.
I've also run into this as well. I had found a little bit of white space at the end of the line was enough for my SMTP service to recognize the new line
body = 'value of variable x = ' + myVarX + " \r\n" \
+ 'value of variable y = ' + myVarY
I believe this to be more of a SMTP issue, rather than a Python issue, which may explain the range in solutions in this thread
Setting the content-type header to Content-Type: text/plain (with \r\n at the end) allowed me to send multi-line plain-text emails.
Outlook will remove line feeds from plain text it believes are extras. https://support.microsoft.com/en-us/kb/287816
You can try below update to make the lines look like bullets. That worked for me.
body = "Dear Student, \n- Please send your report\n- Thank you for your attention"
I ran into this issue as well and this thread was helpful in determining why it was happening in the first place. I was at a lost, because I knew my code was correct. I tried a few things, but what worked for me was adding a \t\n for each line in the body.
from email.mime.text import MIMEText
lines = ['line1', 'line2', 'line3']
body = '\t\n'.join(lines)
msg = MIMEText(body)
please check the version of python.
for version 3.11.1,
you should use '\r\n' for line break
reference the official doc https://docs.python.org/3/library/smtplib.html#:~:text=using%20BytesGenerator%20with-,%5Cr%5Cn%20as%20the%20linesep,-%2C%20and%20calls%20sendmail
Adding \n\n works for me
body = """"""
body += "This is message1\n\n"
body += "This is message2"
Output:
This is message1
This is message2
I am trying to send an email. The code I am using is found below:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
email_user = 'email#gmail.com'
email_password = 'password'
email_send = 'receiver#gmail.com'
subject = 'subject'
msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email_send
msg['Subject'] = subject
body = 'Hi there, sending this email from Python!'
msg.attach(MIMEText(body,'plain'))
try:
text = msg.as_string()
server = smtplib.SMTP('smtp.gmail.com', port=587)
server.starttls()
server.login(email_user, email_password)
server.sendmail(email_user,email_send,text)
server.quit()
print('successfully sent the mail')
except:
print("failed to send mail")
I get an error "failed to send mail" with the error message:
SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials t10sm6451859wra.16 - gsmtp')
The error occurs on the server.login() line, I am not able to login.
I checked other post and it says, it has to do with wrong credentials but my credentials are correct. I have check and double checked.
What could be the problem with this and how do I resolve it?
Send an email using python is easy, you may have encountered mistakes in your snippet code above and I am lazy to debug your code. But here might be the code you prefer.
The smtp.gmail.com,465 make your code secure. This snippet of code will send email to recipient through spam but lot number of emails you wish to send, will not be blocked by Gmail, you also can use bot to send email through recipient via this snippet of code.
Send Multiple Recipients
In the to line, just separate recipients by comma
to = [
'<recipient_email_address1>',
'<recipient_email_address2>',
'<recipient_email_address3>']
import smtplib
def sendEmailFunc():
gmail_user = '<your_sender_email_address_here>'
gmail_password = '<credential_password_of_above_email>'
sent_from = gmail_user
to = ['<recipient_email_address>']
subject = '<write_your_email_subject_here>'
body = "<write_your_email_body_here>"
email_text = """
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_user, gmail_password)
server.sendmail(sent_from, to, email_text)
server.close()
print ('====Email Sent Successfully====')
except:
print ('Something went wrong...')
NOTE
Please be careful with your indentation.
Hope this helpful for you.
Thank you.
I want to send a status mail once a day using a cron job using smtplib.
Sending of the mail works well, however the sending time and date always seems to be the time and date when I read the mail, but not when the mail is sent. This may be 6 hours later.
I have not found hints on providing a sending time to smtplib, together with the message data. Am I missing anything or is this a problem with my mail server configuration? However, other mails handed in via Thunderbird do not show this effect with this account.
My python program (with login data removed) is listed below:
import smtplib
sender = 'abc#def.com'
receivers = ['z#def.com']
message = """From: Sender <abc#def.com>
To: Receiver<z#def.com>
Subject: Testmail
Hello World.
"""
try:
smtpObj = smtplib.SMTP('mailprovider.mailprovider.com')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
[EDIT]
Code using email package as suggested, but still the time shown in my inbox is reading time and not sending time.
import smtplib
from email.mime.text import MIMEText
sender = ..
receiver = ..
message = "Hello World"
msg = MIMEText(message)
msg['Subject'] = 'Testmessage'
msg['From'] = sender
msg['To'] = receiver
try:
s = smtplib.SMTP(..)
s.sendmail(sender, receiver, msg.as_string())
s.quit()
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
Adding an explicit Date field to the message did the trick, thank you to Serge Ballesta for the idea:
import smtplib
from email.utils import formatdate
from email.mime.text import MIMEText
sender = ..
receiver = ..
message = "Hello World"
msg = MIMEText(message)
msg['Subject'] = 'Testmessage'
msg['From'] = sender
msg['To'] = receiver
msg["Date"] = formatdate(localtime=True)
try:
s = smtplib.SMTP(..)
s.sendmail(sender, receiver, msg.as_string())
s.quit()
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
You might have to specify more information in the headers of your message. Try using the email module to build your message instead of assembling the text yourself.
Perhaps it's stupid, but do you have correct date and time on the server?
I'm trying to send an email using a Python script and smtp (I made an account on sendgrid.com), and I found this code on http://www.mkyong.com/python/how-do-send-email-in-python-via-smtplib/ and I can make it work just fine for gmail, but no other domain seems to receive their test mail. When I check my email activity on sendgrid.com, it tells me the emails have been dropped or bounced because they aren't RFC 5322 compliant. I tried to google this error, but I just can't seem to find a solution.
This is what I have so far:
import smtplib
to = 'example#hotmail.com'
user = 'username'
pwd = 'password'
smtpserver = smtplib.SMTP("smtp.sendgrid.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(user, pwd)
header = 'To:' + to + '\n' + 'From: ' + user + '\n' + 'Subject:Test! \n'
print header
msg = header + '\n Test message \n\n'
smtpserver.sendmail(user, to, msg)
print 'Done!'
smtpserver.close()
Feel free to help me out!