Receiving wrong subject - python

I'm using this code to send email and it works, but when I receive email the subject looks like this and also has no message:
" No subject"
afsagsag#gmail.com To: Subject: OMG Super Important Message Good morning, <afsagsag#gmail.com>
import smtplib
import carriers
def amtg():
gmail_user = 'sgfsfsfsf#gmail.com'
gmail_password = 'rtgassds'
sent_from = gmail_user
to = ['sgssfsd#gmail.com']
subject = 'OMG Super Important Message'
body = carriers.rsting + carriers.amtg1
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!')
except:
print ('Something went wrong...')

Related

How do you prevent smtplib library from sending no subject?

for i in range(3):
gmail_user = 'email'
gmail_password = 'pass'
sent_from = gmail_user
to = ['email']
subject = 'Lorem ipsum dolor sit amet'
body = rand_quote
email_text = ("""\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body))
try:
smtp_server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
smtp_server.ehlo()
smtp_server.login(gmail_user, gmail_password)
smtp_server.sendmail(sent_from, to, email_text)
smtp_server.close()
print ("Email sent successfully!")
except Exception as ex:
print ("Something went wrong….",ex)
When I remove the for loop the code runs great with the subject and body sending properly however when I try to run something like the code above the email comes is sent as such.
When you moved text """ """ then it added spaces before From:, To:, Subject: and it treads it as part of body.
You have to move all lines in """ """ to the left.
for i in range(3):
gmail_user = 'email'
gmail_password = 'pass'
sent_from = gmail_user
to = ['email']
subject = 'Lorem ipsum dolor sit amet'
body = rand_quote
email_text = ("""\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body))
try:
smtp_server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
smtp_server.ehlo()
smtp_server.login(gmail_user, gmail_password)
smtp_server.sendmail(sent_from, to, email_text)
smtp_server.close()
print ("Email sent successfully!")
except Exception as ex:
print ("Something went wrong….",ex)
BTW:
See also #tripleee comment below.
Some examples in documentation: email.examples

Cant send subject in email - python

when i send an email message like this i cant get the subject get into the message(i get it in the body). what can i do to change it? thank you!
def SendEmailNotHTML(EmailToList,EmailBody,EmailSubject):
mail_from = settings.SMTP_USER
try:
for current_mail_to in EmailToList:
fromaddr = settings.SMTP_USER
toaddrs = current_mail_to
msg = "\r\n".join([
"Subject: {0}".format(EmailSubject),
"",
"{0}".format(EmailBody)
])
print(msg)
my_email = MIMEText(msg, "plain")
username = settings.SMTP_USER
password = settings.SMTP_PASSWORD
server = smtplib.SMTP('smtp.gmail.com:25')
server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, my_email.as_string())
server.quit()
except Exception as e:
print('cant send email' + str(e))

Sending mail via Python with cyrillic characters

The problem is in subject. That's ok when I do
import smtplib
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login(".....#gmail.com", "........")
message = u"бла бла бла".encode('utf8')
s.sendmail(".....#gmail.com", ".....#gmail.com", message)
But I get an error when I do
subject = u'бла бла бла'.encode('utf8')
body = u'бла бла бла'.encode('utf8')
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.com", ".......")
server.sendmail(sent_from, to, email_text)
s.quit()
print ('Email sent!')
except:
print ('Something went wrong...')
I add
from email.mime.text import MIMEText
subject = MIMEText('текст 1', 'plain')
body = MIMEText('текст 2', 'plain')
then again
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login("......#gmail.com", ".......")
server.sendmail(sent_from, to, email_text)
s.quit()
print ('Email sent!')
except:
print ('Something went wrong...')
I get the letter but
in subject field
Content-Type: text/plain; charset="utf-8"
In body field
текст 1
i.e in body field I get text from subject. Ho to fix it?
Just to add
from email.header import Header
Subject= Header('бла бла бла', 'utf-8')
Sorry
This what worked for me
part.add_header('content-disposition', 'attachment', filename=('utf-8', '', ATTACHMENT_NAME))
Complete code sample for sending email with attachment:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
ATTACHMENT_NAME = 'отчет.xlsx'
def send_email():
msg = MIMEMultipart()
msg['Subject'] = EMAIL_SUBJECT
msg['From'] = USERNAME
msg['To'] = ", ".join(RECIPIENTS)
msg.attach(MIMEText(EMAIL_TEXT))
with open(REPORT_FILE, 'rb') as f:
part = MIMEBase('application', "octet-stream")
part.set_payload(f.read())
encoders.encode_base64(part)
part.add_header('content-disposition', 'attachment', filename=('utf-8', '', ATTACHMENT_NAME))
msg.attach(part)
s = smtplib.SMTP(SERVER)
s.login(USERNAME, PASSWORD)
s.sendmail(USERNAME, RECIPIENTS, msg.as_string())
s.quit()

Giving a class it parameters from other classes-Python

I have a class sendmail and I am trying to call it in other classes.The argument will determine which email to send. The argument in the sendmail class will send mail according to parameters given to it from other classes where it is being called.However,when executing it, I get error message saying argument not defined.
Here is my code:
#!/usr/bin/python
import smtplib
class sendmail(argument):
TO = 'yourmail#gmail.com'
if argument=='PIR':
SUBJECT = 'PIR'
TEXT = 'Motion is detected'
gmail_sender = 'mymail#gmail.com'
gmail_passwd = 'mypwd'
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo
server.login(gmail_sender, gmail_passwd)
BODY = '\r\n'.join([
'TO: %s' % TO,
'From: %s' % gmail_sender ,
'Subject: %s' % SUBJECT ,
'',
TEXT
])
try:
server.sendmail(gmail_sender, [TO], BODY)
print 'email sent'
except:
print 'error'
server.quit()
I think what you're looking for is a static function.
import smtplib
class MailUtils:
#staticmethod
def sendmail(argument):
TO = 'yourmail#gmail.com'
if argument=='PIR':
SUBJECT = 'PIR'
TEXT = 'Motion is detected'
gmail_sender = 'mymail#gmail.com'
gmail_passwd = 'mypwd'
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo
server.login(gmail_sender, gmail_passwd)
BODY = '\r\n'.join([
'TO: %s' % TO,
'From: %s' % gmail_sender ,
'Subject: %s' % SUBJECT ,
'',
TEXT
])
try:
server.sendmail(gmail_sender, [TO], BODY)
print 'email sent'
except:
print 'error'
server.quit()
You would use it by doing this:
import MailUtils
MailUtils.sendmail(argument)
Note: As mentioned in the comments below, this approach works best if the class contains multiple related functions, not just a single one.

Why is the email not sending to the recipient?

This is the code I have running, which is supposedly working totally fine, but it is not actually sending the email to the address I specify. It does not have anything to do with the CSV because I have another script doing the same thing and working just fine. The problem is that the email is being placed in the senders inbox... which is weird.
I would rather use this script since it's nicely object oriented and it has all the proper subject fields, etc.
import smtplib
import pandas as pd
class Gmail(object):
def __init__(self, email, password, recepient):
self.email = email
self.password = password
self.recepient = recepient
self.server = 'smtp.gmail.com'
self.port = 465
session = smtplib.SMTP_SSL(self.server, self.port)
session.ehlo
session.login(self.email, self.password)
self.session = session
print('Connected to Gmail account successfully.')
def send_message(self, subject, body):
headers = [
"From: " + self.email,
"Subject: " + subject,
"To: " + self.recepient,
"MIME-Version: 1.0",
"Content-Type: text/html"]
headers = "\r\n".join(headers)
self.session.sendmail(
self.email,
self.email,
headers + "\r\n\r\n" + body)
print('- Message has been sent.')
df = pd.read_csv('test.csv', error_bad_lines=False)
for index, row in df.iterrows():
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
comp_name = (row['name'])
print('Email to: ' + comp_name)
rec = (row['email'])
print('Email to: ' + rec)
gm = Gmail('email#gmail.com', 'password', rec)
gm.send_message('email to ' + comp_name, '<b>This is a test<b>')
print('-- Message for ' + rec + ' (' + comp_name + ') is completed.')
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
print('*********************************')
print('Finish reading through CSV.')
print('*********************************')
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
Let me know if there is something wrong. I would really like this to work.
Just so that you can see it is working, here is the other script I am testing it against (which is poorly formatted) and it is completely functioning properly.
import smtplib
import pandas as pd
df = pd.read_csv('test.csv', error_bad_lines=False)
gmail_user = 'email#gmail.com'
gmail_password = 'password'
for index, row in df.iterrows():
sent_from = gmail_user
to = (row['email'])
subject = 'Important Message'
body = 'Hey, whats up'
rec = (row['email'])
comp_name = (row['name'])
print('Email to: ' + comp_name)
print('Email to: ' + rec)
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, 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!')
except:
print ('-- Something went wrong...')
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
print('*********************************')
print('Finish reading through CSV.')
print('*********************************')
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
You should pass the recipient instead of the sender.
self.session.sendmail(
self.email,
# self.email, <- wrong here
self.recepient,
headers + "\r\n\r\n" + body)

Categories

Resources