sent mail from python CGI - Error - python

I'm trying to send a mail with from cgi web console using email input field but it fails with below error in apache logs
Traceback (most recent call last):
File "/opt/apache-dba/cgi-bin/main.py", line 132, in <module>
mail()
File "/opt/apache-dba/cgi-bin/main.py", line 129, in mail
s.sendmail(me, you, msg.as_string())
File "/usr/lib64/python2.7/smtplib.py", line 742, in sendmail
raise SMTPRecipientsRefused(senderrs)
smtplib.SMTPRecipientsRefused: {'xxx#adp.com/': (501, '5.1.3 Bad recipient address syntax')}
But I'm able to run the same code and able to receive the mail from python shell
Below is the code, this looks like when I run the code from cgi it is trying to convert mailid from 'xxx#adp.com' to 'xxx#adp.com/' resulting syntax error.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
Emailid = xxx#gmail.com
Link='http://google.com'
def mail():
me = "GETS.INDIA.DDS.TAM#gmail.com"
you = str(Emailid)
msg = MIMEMultipart('alternative')
msg['Subject'] = "Upgrade Status Link"
msg['From'] = me
msg['To'] = you
text = '%s' % str(Link)
part1 = MIMEText(text, 'plain')
msg.attach(part1)
s = smtplib.SMTP('localhost')
s.sendmail(me, you, msg.as_string())
s.quit()
mail()
any help will be greatly appreciated, Thank you

It looks like Emailid should be a string. Try surrounding your test email in quotes to make it a string.
Emailid = 'xxx#gmail.com'

Related

TypeError: 'utf8' is an invalid keyword argument for Compat32 smtplib email error message

I have been able to send personalized emails using the script below before, but all of a sudden I am getting the following error.
I am trying to read names and email ID's from a file and send a personalized email to each person. It picks a random subject from the list of subjects and uses a random delay. It worked fine until now but it won't now.
*Traceback (most recent call last):
File "C:/myprojects/normal_email.py", line 64, in <module>
main()
File "C:/myprojects/normal_email.py", line 57, in main
smtp.send_message(msg)
File "C:\Python\lib\smtplib.py", line 964, in send_message
bytesmsg, policy=msg.policy.clone(utf8=True))
File "C:\Python\lib\email\_policybase.py", line 72, in clone
raise TypeError(
TypeError: 'utf8' is an invalid keyword argument for Compat32*
import csv
from string import Template
import smtplib
import random
import time
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
template_file = r'C:\Users\91880\Desktop\template.txt'
filename = r'C:\Users\91880\Downloads\2307.csv'
# reads the file and returns the names, emails in a list
def get_contacts(file):
names_list = []
emails_list = []
with open(file, 'r') as mail_data:
data = csv.reader(mail_data)
for details in data:
names_list.append(details[0])
emails_list.append(details[1])
return names_list, emails_list
# reads the template from a text file and returns
def get_template(file):
with open(file, 'r') as template_info:
template_data = template_info.read()
return Template(template_data)
def main():
email_user = 'myemail#mail.com'
password = 'mypassword'
subs = ['Hi', 'Hello']
names, emails = get_contacts(filename)
template = get_template(template_file)
with smtplib.SMTP('smtp.office365.com', '587') as smtp:
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login(email_user, password)
for name, email in zip(names, emails):
subject = random.choice(subs)
number = random.randint(10, 30)
msg = MIMEMultipart()
message = template.substitute(name=name.title())
msg['From'] = email_user
msg['To'] = email
msg['Subject'] = subject
msg.attach(MIMEText(message, 'html'))
smtp.send_message(msg)
print(f'sent email to {name} at {email}')
del msg
time.sleep(number)
if __name__ == '__main__':
main()
This error occurs because there is at least one non-ascii character in one of the "to" or "from" addresses. It should be possible to fix it by setting the policy on the message to email.policy.default:
from email import policy
...
msg = MIMEMultipart(policy=policy.default)
The newer EmailMessage/EmailPolicy API is preferred over the old email.mime tools since Python 3.6. Using the preferred tools, the code would look like this:
from email.message import EmailMessage
from email import policy
...
msg = EmailMessage(policy=policy.default)
message = template.substitute(name=name.title())
msg['From'] = email_user
msg['To'] = email
msg['Subject'] = subject
msg.set_content(message, subtype='html')
smtp.send_message(msg)
For absolute RFC compatibility, you might consider setting the policy to SMTP, to generate \r\n line endings.

Python script to send mail

import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login("******#gmail.com", "*******")
msg = "Hello!"
server.sendmail("rajesh.debugs#gmail.com", "rjucsm#gmail.com", msg)
OUTPUT :
C:\Users\Admin\PycharmProjects\Gabbar\venv\Scripts\python.exe C:/Users/Admin/PycharmProjects/Gabbar/MadhuBhai/t3.py
Traceback (most recent call last):
File "C:/Users/Admin/PycharmProjects/Gabbar/MadhuBhai/t3.py", line 5, in <module>
server.login("******#gmail.com", "******")
File "C:\Users\Admin\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 730, in login
raise last_exception
File "C:\Users\Admin\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 721, in login
initial_response_ok=initial_response_ok)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 642, in auth
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbtX\n5.7.14 HDzghr7H0UegF2rvoxWT6p9FwK8ct-IgZQXTa09qiineo743EE4PjOLOukbW-7fN2_FfIx\n5.7.14 qBwOghPCGmq1zlaUP3231EHWXgeut6dhRtiEjEVKAd-VKglbnUqvCyPMLKlADKhWt56L_5\n5.7.14 afzoYLGapj8SmZxp_W6VMrkj10aK9xthTsrmUerV9bkqgILAnKh9SWOO2n-7WsHO43reIf\n5.7.14 MQqmW0G2lyXQWbYt-8LxUHRt3ATI8> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 v5-v6sm6337091pfd.1 - gsmtp')
Process finished with exit code 1
Possible duplicate of: SMTPAuthenticationError when sending mail using gmail and python
You will need to look at https://support.google.com/accounts/answer/6010255?hl=en and enable https://myaccount.google.com/lesssecureapps for your mail account.
If you aren't set on using with smtplib, then I would recommend SendGrid for sending emails (if you send < 100 emails/day then it's free).
import sendgrid
from sendgrid.helpers.mail import *
sg = sendgrid.SendGridAPIClient(apikey=sendgrid_api_key)
from_email = Email("test#example.com")
to_email = Email("test#example.com")
subject = "Sending with SendGrid is Fun"
content = Content("text/plain", "content")
mail = Mail(from_email, subject, to_email, content)
response = sg.client.mail.send.post(request_body=mail.get())
print(response.status_code)
You need to use email.mime along with smtp. Try below:
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import smtplib
strFrom = 'xyz.uvw#gmail.com'
strTo = ['efg.abc#gmail.com','hij.lmn#gmail.com']
attachment = '<path to attachment if any>'
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'TEST'
msgRoot['From'] = strFrom
msgRoot['To'] = ", ".join(strTo)
msgRoot.preamble = 'This is a multi-part message in MIME format.'
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
msgText = MIMEText('This is the alternative plain text message.')
msgAlternative.attach(msgText)
msgText = MIMEText('<b>Summary</b>', 'html')
msgAlternative.attach(msgText)
fp = open(attachment, 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)
smtp = smtplib.SMTP("YOUREMAILHOST", 25, timeout=120)
smtp.sendmail(strFrom, strTo, msgRoot.as_string())
smtp.close()

Sending multiple emails with python

I'm trying to create a daemon which regularly sends me emails and I'm using the following snippet of code to do so.
import smtplib
from datetime import date
from email.mime.text import MIMEText
def send_email():
SMTP_PORT = 587
SMTP_SERVER = 'smtp.mail.com'
SMTP_USERNAME = 'EMAIL'
SMTP_PASSWORD = 'PASSWORD'
EMAIL_TO = ['email#hotmail.com']
EMAIL_FROM = 'EMAIL'
EMAIL_SUBJECT = 'Test!'
DATE_FORMAT = '%d/%m/%Y'
EMAIL_SPACE = ', '
DATA='Email Content'
msg = MIMEText(DATA)
msg['Subject'] = EMAIL_SUBJECT + ' %s' % (date.today().strftime(DATE_FORMAT))
msg['To'] = EMAIL_SPACE.join(EMAIL_TO)
msg['From'] = EMAIL_FROM
mail = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
mail.starttls()
mail.login(SMTP_USERNAME, SMTP_PASSWORD)
mail.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
mail.quit()
However, after 5 emails, even though I've added the senders email to my contact list on outlook/hotmail, the daemon returns the following exception:
Sending email! 1/1
Traceback (most recent call last):
File "daemon.py", line 91, in <module>
send_email()
File "daemon.py", line 78, in send_email
mail.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 742, in sendmail
raise SMTPRecipientsRefused(senderrs)
smtplib.SMTPRecipientsRefused: {'email#hotmail.com': (550, 'Requested action not taken: mailbox unavailable\nFailure sending mail. Try again later')}
Can anyone advise on how to get around this? Does anyone know of an email service that has been tested which will allow more than 5 emails or how I configure the smtplib to not stop sending after 5 emails to the same address?
UPDATE: When I change the receiving email address from outlook to gmail (another one of my emails) - it returns the same exception even though I've sent no emails to the gmail SMTP server.

How to send email while keeping the To: list blank and only Bcc: list populated using sendmail function of smtplib in python

I am new to Python. I have a case where I need to send email where the Bcc: list must be populated and To: list must be blank in order to hide the recipients identity.
I gave msg['TO']as '', None, [''], []. None of these worked.
I Googled, but found nothing related to my problem. I kept To: list blank in my code and some email ids in Bcc: list, then ran my code and got the following error:
Traceback (most recent call last):
File "C:\Users\script.py", line 453, in send_notification
smtp.sendmail(send_from, send_to, msg.as_string())
File "C:\Python27\lib\smtplib.py", line 742, in sendmail
raise SMTPRecipientsRefused(senderrs)
SMTPRecipientsRefused: {'': (555, '5.5.2 Syntax error. hb1sm19555493pbd.36 - gsmtp')}
Following is my code:
msg['From'] = send_from
msg['To'] = ''
msg['Subject'] = subject
msg['BCC'] = COMMASPACE.join(send_to)
I'm pretty sure all emails are required to have a To address. (Edit: Actually, they're not)
Whenever I receive emails that were sent to an anonymized list like what you're describing, the To and From addresses are generally both the same, which is a reasonable workaround. It looks pretty clean to the recipient:
To: some-student-org#my-university.edu
From: some-student-org#my-university.edu
Bcc: me
If you want to bcc using python's smtplib, don't include the bcc header, just include the bcc recipients in the call to smtplib.sendmail. For your specific example:
import smtplib
from email.mime.text import MIMEText
smtp_server = 'localhost'
send_from = 'your#email.com'
send_to = ['one#email.com', 'two#email.com']
msg_subject = 'test'
msg_text = 'hello'
msg = MIMEText(msg_text)
msg['Subject'] = msg_subject
msg['From'] = send_from
smtp = smtplib.SMTP()
smtp.connect(smtp_server)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.quit()

Email using Python with Excel attachment

#!/usr/bin/env python3
import smtplib,email,email.encoders,email.mime.text,email.mime.base
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart()
# me == my email address
# you == recipient's email address
me = "sender#email.com"
you = "reciever#email.com "
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('mixed')
msg['Subject'] = "msg"
msg['From'] = me
msg['To'] = you
# Create the body of the message (a plain-text and an HTML version).
text = "Hi\nThis is text-only"
html = """\
<html> This is email</html>
"""
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
#attach an excel file:
fp = open('TestStatus.xlsx', 'rb')
file1=email.mime.base.MIMEBase('application','vnd.ms-excel')
file1.set_payload(fp.read())
fp.close()
email.encoders.encode_base64(file1)
file1.add_header('Content-Disposition','attachment;filename=anExcelFile.xlsx')
# 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(part2)
msg.attach(part1)
msg.attach(file1)
composed = msg.as_string()
fp = open('msgtest.eml', 'w')
fp.write(composed)
# Credentials (if needed)
# The actual mail send
server = smtplib.SMTP('dc1smtp.com')
server.starttls()
server.sendmail(me, you, msg)
server.quit()
fp.close()
also when running it, I see this error message.
Traceback (most recent call last):
File "excel.py", line 57, in <module>
server.sendmail(me, you, msg)
File "C:\Python33\lib\smtplib.py", line 775, in sendmail
(code, resp) = self.data(msg)
File "C:\Python33\lib\smtplib.py", line 516, in data
q = _quote_periods(msg)
File "C:\Python33\lib\smtplib.py", line 167, in _quote_periods
return re.sub(br'(?m)^\.', b'..', bindata)
File "C:\Python33\lib\re.py", line 170, in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or buffer
I have tested this code and it is working. the only problem i am having is that, when i run it, i dont recieve the emails that i am testing it with. But when i run this code. it creates a file named "msgtest.eml". This file is like a draft of my email or something.
can someone show me how to use this show and be an actually email instead of a draft?
thanks
To send mail from localhost:
import smtplib
me = "me#me.com"
you = "you#you.com"
# insert your code here
msg = ...
s = smtplib.SMTP('localhost')
s.sendmail(me, [to], msg.as_string())

Categories

Resources