Python: How to pass email text body to Office365 Email - python

Trying to make the script below work for office365. Sends out an email but I cannot get the script to recognize the actual email text body (only the Subject line being sent). Below script worked for gmail. Any ideas where I need to modify?
Thanks!
import smtplib, ssl
port = 587
smtp_server = "smtp.office365.com"
sender_email = "me#email.com"
receiver_email = {'User1': 'user1#email.com'}
password = "password"
subject = input('Enter the subject line: ')
message = input('Enter the message: ')
email = """\
Subject: %s
%s
""" % (subject, message)
for key, value in receiver_email.items():
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
server.ehlo() # Can be omitted
server.starttls(context=context)
server.ehlo() # Can be omitted
server.login(sender_email, password)
server.sendmail(sender_email, value, email)
server.quit()

was missing a "\n" in the email object. It now works.
email = """\
Subject: %s\n
%s
""" % (subject, message)

Related

sending email using smtplib and SSL but receiver is no receiving it

I am trying to send email from one email to another using smtplib and ssl. It's showing delivered, but there is no email at receiver end. I am trying two different codes:
Code 1:
import smtplib, ssl
port = 465
smtp_server = "myserver.com"
sender_email = "sender#myserver.com"
receiver_email = "receiver#gmail.com"
password = "mypassword"
message = """\
Subject: Hi there
This message is sent from Python."""
try:
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
print("Sent..")
except:
print("Error!!")
code 2:
import smtplib
import os.path
from email.mime.text import MIMEText
msg = MIMEText("")
msg['Subject'] = "Hi there, This message is sent from Python."
s = smtplib.SMTP_SSL("myserver.com:465")
s.login("sender#myserver.com","mypassword")
s.sendmail("sender#myserver.com","receiver#gmail.com", msg.as_string())
s.quit()
print("done")
Can not find the problem. Any idea?
The sendmail method is a low level method that assumes that the message text is correctly formatted. And your messages do not contain the usual To: and From: headers.
The send_message method uses an EmailMessage and formats it correctly, so it can be easier to use. I would advise to change your code to:
port = 465
smtp_server = "myserver.com"
password = "mypassword"
msg = MIMEText("This message is sent from Python.")
msg['Subject'] = "Hi there"
msg['From'] = "sender#myserver.com"
msg['To'] = "receiver#gmail.com"
try:
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.send_message(msg)
print("Sent..")

E-mail sent with smtplib ends as spam

I have the following code:
import smtplib, ssl
def send_email(temperature):
port = 465 # For SSL
password = "my_password"
sender_email = "my_sender#gmail.com"
receiver_email = "my_receiver#x.y"
message = """\
Subject: Temperature is %0.2f degrees C
""" % temperature
server = smtplib.SMTP_SSL("smtp.gmail.com", port)
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
if __name__ == "__main__":
send_email(7.7)
After the first run, the first message was received OK.
Next messages were in a spam folder without sender address, subject and body. I tried to mark it
as not spam, but it didn't help.
The message headers have the correct sender address, subject and body.
Can I correct it somehow?
I solved it as follows:
import smtplib, ssl
from email.mime.text import MIMEText
def send_email(temperature):
port = 465 # For SSL
password = "my_password"
sender_email = "my_sender_address#gmail.com"
receiver_email = "my_receiver_address.x.y"
message = MIMEText("Temperature is %0.2f degrees" % temperature)
message['Subject'] = "%0.2f degrees" % temperature
message['From'] = sender_email
message['To'] = receiver_email
server = smtplib.SMTP_SSL("smtp.gmail.com", port)
server.login(sender_email, password)
server.sendmail(sender_email, [receiver_email], message.as_string())
server.quit()
if __name__ == "__main__":
send_email(7.7)

Using function to send gmails via python

Below are 2 code blocks. The first will send a message to gmail with the correct subject and sender. However, when I put the first code into a function, the email loses the sender and subject info.
Why is this and how do I fix it?
I would like to be able to call this function from other python scripts to notify me when my job is complete. The function works and runs without error, and the email makes it to my inbox, but I lose the sender info and more importantly, the subject heading.
1st code that runs as expected:
import smtplib
gmail_user = 'name#domain.com'
gmail_password = 'password'
sent_from = gmail_user
to = ['recipient#domain.com']
subject = "job complete"
body = "python script " + str(name) + " has finished"
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
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()
2nd code that loses subject and sender info:
def mailer(subject, body):
import smtplib
gmail_user = 'name#domain.com'
gmail_password = 'password'
sent_from = gmail_user
to = ['recipient#domain.com']
subject = subject
body = body
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
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()
subject = "job complete"
body = "python script " + str(name) + " has finished"
mailer(subject, body)
It's most likely a line ending issue. Each mail headers is required to end with CRLF (\r\n). The original message string may have contained the correct endings (invisible in the editor) which were subsequently lost during copy/paste to the function version. To ensure that each line is ended correctly, try expressing each as a separate string and joining them with \r\n.
email_text = '\r\n'.join([
'From: %s' % sent_from,
'To: %s' % ', '.join(to),
'Subject: %s' % subject',
'', # Blank line to signal end of headers
body
])

Sending Verizon SMS message via Python and smtplib

I can make smtplib send to other email addresses, but for some reason it is not delivering to my phone.
import smtplib
msg = 'test'
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login("<username>","<password>")
server.sendmail(username, "<number>#vtext.com", msg)
server.quit()
The message sends successfully when the address is a gmail account, and sending a message to the phone using the native gmail interface works perfectly. What is different with SMS message numbers?
Note: using set_debuglevel() I can tell that smtplib believes the message to be successful, so I am fairly confident the discrepancy has something to do with the behavior of vtext numbers.
The email is being rejected because it doesn't look an email (there aren't any To From or Subject fields)
This works:
import smtplib
username = "account#gmail.com"
password = "password"
vtext = "1112223333#vtext.com"
message = "this is the message to be sent"
msg = """From: %s
To: %s
Subject: text-message
%s""" % (username, vtext, message)
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(username,password)
server.sendmail(username, vtext, msg)
server.quit()
The accepted answer didn't work for me with Python 3.3.3. I had to use MIMEText also:
import smtplib
from email.mime.text import MIMEText
username = "account#gmail.com"
password = "password"
vtext = "1112223333#vtext.com"
message = "this is the message to be sent"
msg = MIMEText("""From: %s
To: %s
Subject: text-message
%s""" % (username, vtext, message))
server = smtplib.SMTP('smtp.gmail.com',587)
# server.starttls()
server.login(username,password)
server.sendmail(username, vtext, msg.as_string())
server.quit()

Python: Email problem

I'm using the script below to send an email to myself, the script runs fine with no errors but I don't physically receive an email.
import smtplib
sender = 'foo#hotmail.com'
receivers = ['foo#hotmail.com']
message = """From: From Person <foo#hotmail.com>
To: To Person <foo#hotmail.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
EDIT
The script is named test.py
Why you use localhost as the SMTP?
If you are using hotmail you need to use hotmail account, provide the password, enter port and SMTP server etc.
Here is everything you need:
http://techblissonline.com/hotmail-pop3-and-smtp-settings/
edit:
Here is a example if you use gmail:
def mail(to, subject, text):
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
Encoders.encode_base64(part)
msg.attach(part)
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
# Should be mailServer.quit(), but that crashes...
mailServer.close()
I have something to add to Klark's great answer. When I try:
Encoders.encode_base64(part)
I received an error
NameError: global name 'Encoders' is not defined
It should be
encoders.encode_base64(msg)
https://docs.python.org/2/library/email-examples.html
Jeff Atwood's blog post from last April may be of some help.
The "localhost" SMTP server won't work with Hotmail. You'll have to hard-code your password in so Hotmail can authenticate you as well. The default SMTP for Hotmail is "smtp.live.com" on port 25. Try:
import smtplib
sender = 'foo#hotmail.com'
receivers = ['foo#hotmail.com']
password = 'your email password'
message = """From: From Person <foo#hotmail.com>
To: To Person <foo#hotmail.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP("smtp.live.com",25)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.ehlo()
smtpObj.login(sender, password)
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"

Categories

Resources