Python 2.7 / Windows : Very odd behavior sending SMTP email - email

This has me totally stumped. Here are two simple routines that send an email. The first succeeds, the second (with some minor exception trapping) locks up Python (Cntl-C will not kill the session). In addition I've determined that the quote type used for the "Subject" line matters. So if I use
msg['Subject'] = "Random text"
The email will fail, but
msg['Subject'] = 'Random text'
this succeeds
Can someone please shine some light into the darkness:
Example #1
import smtplib
from email.mime.text import MIMEText
addr = "10.0.0.178"
From = "me#somewhere.net"
recip = ["me#somewherelese.net","foo#bar.net"]
msg = "Message Body"
send_email(recip,"Subject Line",msg)
def send_email(To,Subj,Mess):
msg = MIMEText(Mess)
msg["Subject"] = Subj
msg['From'] = From
s = smtplib.SMTP(addr)
for entry in To:
msg['To'] = entry
s.sendmail(From, [entry], msg.as_string())
s.quit()
Example 2:
import smtplib
from email.mime.text import MIMEText
addr = "10.0.0.178"
From = "me#somewhere.net"
recip = ["me#somewherelese.net","foo#bar.net"]
msg = "Message Body"
send_email(recip,"Subject Line",msg)
def send_email(To,Subj,Mess):
msg = MIMEText(Mess)
msg["Subject"] = Subj
msg['From'] = From
s = smtplib.SMTP(addr)
for entry in To:
msg['To'] = entry
try:
s.sendmail(From, [entry], msg.as_string())
except:
print "Error sending email"
s.quit()

Related

Python e-mail attachment as xlsx doesnot work when I set name as a variable

I would like to send auto-mails to from time to time, and attach an excel file to the mail. It's okay if I write the name of the excel file straight ahead, however if I link it to a variable , what happens is a formatless file attached.e-mail view at inbox
Briefly, I want this line to work with a variable called attachmentFile rather than writing "2020-01-01.xlsx"
part.add_header('Content-Disposition', 'attachment; filename="attachmentFile"')
import smtplib,ssl
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import formatdate
from email import encoders
attachmentFile="2021-01-02.xlsx"
def send_mail():
send_from= 'spotalert#****.com'
send_to='deniz.yildirim#****.com'
subject = 'Uygunsuz Punta Bildirimi'
body_1='Merhaba\n'
body_2= 'xxxxx Nolu Punta Tahribatli kontrolde uygunsuz cikmistir.\n'
body_3='Uygunsuzluk sebebi = xxxxxxx ' + 'Puntanin Bulundugu Posta :'+'\n'
body_4= ' Bu otomatik bir maildir lutfen cevap vermeyiniz.\n'
body_5='Uygunsuzlugun ciktigi tarih'+ '\n'
text = body_1 + body_2 + body_3 + body_4 +body_5
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = send_to
msg['Date'] = formatdate(localtime = True)
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', "octet-stream")
part.set_payload(open(attachmentFile, "rb").read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="2021-01-02.xlsx"')
msg.attach(part)
At the second-last line in your code instead of:
part.add_header('Content-Disposition', 'attachment; filename="2021-01-02.xlsx"')
use this:
part.add_header('Content-Disposition', 'attachment', filename=attachmentFile)

Mail not getting sent through AWS Glue Python job

I am trying to send a mail through an AWS Glue job. The mail will have multiple number of attachments that it gets from the s3 bucket. According to the logs, it is running until server.login(). It is failing in the server.sendmail() function.
Following is the code -
def sendEmail(TO, SUBJECT, BODY_HTML):
msg = MIMEMultipart('alternative')
msg['Subject'] = SUBJECT
msg['From'] = SENDER
msg['To'] = ','.join(RECIPIENT + TO)
part1 = MIMEText(BODY_HTML, 'html')
msg.attach(part1)
s3 = boto3.resource('s3')
bucket = s3.Bucket('sample-bucket')
for obj in bucket.objects.filter(Delimiter='/', Prefix='sample-folder/'):
filename = ((obj.key).split("/")[1])
s3_object = s3_obj.s3_get_object(sample-bucket, 'sample-folder/'+ filename)
body = s3_object['Body'].read()
part = MIMEApplication(body, filename)
part.add_header("Content-Disposition", 'attachment', filename=filename)
msg.attach(part)
try:
server = smtplib.SMTP(HOST, PORT)
server.ehlo()
server.starttls()
server.ehlo()
server.login(USERNAME_SMTP, PASSWORD_SMTP)
server.sendmail(SENDER, RECIPIENT, msg.as_string()) ***--Error***
server.close()
print (msg)
print ("Email sent")
I am getting the following error -
Error: (554, b'Transaction failed: Expected '=', got "null"')
What is the issue?
I got the answer. The problem was with the way files were read from s3. The output of the first iteration was -
sample-bucket/sample-folder/
So, it was taking a null object and failing. So, I just skipped the first object in the iteration and carried out the whole thing. It worked.
Please find the final code below -
def sendEmail(TO, SUBJECT, BODY_HTML):
msg = MIMEMultipart('alternative')
msg['Subject'] = SUBJECT
msg['From'] = SENDER
msg['To'] = ','.join(RECIPIENT + TO)
part1 = MIMEText(BODY_HTML, 'html')
msg.attach(part1)
s3 = boto3.resource('s3')
bucket = s3.Bucket('sample-bucket')
**it = iter(bucket.objects.filter(Delimiter='/', Prefix='sample-folder/'))
next(it, None)
for obj in it:**
filename = ((obj.key).split("/")[1])
s3_object = s3_obj.s3_get_object(sample-bucket, 'sample-folder/'+ filename)
body = s3_object['Body'].read()
part = MIMEApplication(body, filename)
part.add_header("Content-Disposition", 'attachment', filename=filename)
msg.attach(part)
try:
server = smtplib.SMTP(HOST, PORT)
server.ehlo()
server.starttls()
server.ehlo()
server.login(USERNAME_SMTP, PASSWORD_SMTP)
server.sendmail(SENDER, RECIPIENT, msg.as_string())
server.close()
print (msg)
print ("Email sent")

When I try to run this VB Script it says "object required" and I cannot find an error

Dim objMessage
Set objMessage = CreateObject("CDO.Message")
objMessage.Subject = "ALARMNO SPOROĆILO Z NADZORNEGA SISTEMA"
objMessage.From = "someemail#hotmail.com"
objMessage.To = "toemail#hotmail.com"
objMessage.HTMLBody = "Zdravo"
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = 1
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "someemail#gmail"
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "00000000000000"
objMessage.Configuration.Fields.Update
REM Now send the message
On error Resume Next
Obj.Message.Send
IF err.Number <> 0 Then
MsgBox Err.Description,16,"Error sending Mail "
Else
MsgBox " Message sent "
END IF
I wrote this code in Notepad++ and saved it as a .vbs file and try to run it, but I get "object required" error. I cannot find the problem.
'Create the objects require for sending email using CDO
Set objMail = CreateObject("CDO.Message")
Set objConf = CreateObject("CDO.Configuration")
Set objFlds = objConf.Fields
'Set various parameters and properties of CDO object
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'cdoSendUsingPort
'your smtp server domain or IP address goes here such as smtp.yourdomain.com
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
'uncomment next three lines if you need to use SMTP Authorization
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "email#gmail.com"
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "password"
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 'cdoBasic
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = 1
objFlds.Update
objMail.Configuration = objConf
objMail.From = "email#gmail.com"
objMail.To = "email#hotmail.com"
objMail.Subject = "Put your email's subject line here"
objMail.TextBody = "Your email body content goes here"
objMail.Send
'Set all objects to nothing after sending the email
Set objFlds = Nothing
Set objConf = Nothing
Set objMail = Nothing
With little more search i found this on the internet...and it works so if anybody else needs a solution here it is ...also if there is somebody who could explain me where i went wrong in my own script...i would be grateful.
I suspect your original script failed because you had
Obj.Message.Send
... instead of
objMessage.Send

Flask HTML emails is not rendered

I have a flask application, where I want to send an email, along with some data fetched from a form. Everything works fine, but the issue is, that when the email is received the HTML code is not rendered it is only displayed the raw code. Here is what I have done so far
if google_response['success']: #this line is used for a ReCaptcha response
msg = Message('Thank you for contacting me', sender='(my email address is put here as a string)', recipients=[request.form['email']])
name = request.form['name']
msg.body = render_template('email.html', name=name)
mail.send(msg)
return render_template('index.html')
else:
return render_template('index.html')
What, am I doing wrong?
I am assuming this has to do with how you are creating your email. You should be using a Multipart Email to do so. My guess would be that you're using using your HTML as the text for the email and not actually attaching it to the email.
Since you haven't provided us with any of that code, I'll give you an example of how to generate an email that includes HTML formatting.
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
to_address = ''
from_address = ''
msg = MIMEMultipart('alternative')
msg['Subject'] = ''
msg['From'] = from_address
msg['To'] = to_address
text = ''
html = 'your HTML code goes here'
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
msg.attach(part1)
msg.attach(part2)
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
mail.login('', '')
mail.sendmail(to_address, from_address, msg.as_string())
mail.quit()

Issue with smtplib sending mail with unicode characters in Python 3.1

Hello i' ve this problem with unicode emails, when i try to send words in spanish like: "Añadir" or others the system collapse, i've try what says on this link: Python 3 smtplib send with unicode characters and doesn't work.
This is the code of my error:
server.sendmail(frm, to, msg.as_string())
g.flatten(self, unixfrom=unixfrom)
self._write(msg)
self._write_headers(msg)
header_name=h)
self.append(s, charset, errors)
input_bytes = s.encode(input_charset, errors)
UnicodeEncodeError: 'ascii' codec can't encode character '\xf1' in position 7: ordinal not in range(128)
This is the code on the server:
msg = MIMEMultipart('alternative')
frm = "sales#bmsuite.com"
msg['FROM'] = frm
to = "info#bmsuite.com"
msg['To'] = to
msg['Subject'] = "Favor añadir esta empresa a la lista"
_attach = MIMEText("""Nombre:Prueba; Dirección:Calle A #12.""".encode('utf-8'), _charset='utf-8')
msg.attach(_attach)
server.sendmail(frm, to, msg.as_string())
server.quit()
Thanks in advance.
You can instead just use:
msg = MIMEText(message, _charset="UTF-8")
msg['Subject'] = Header(subject, "utf-8")
But either way you still have issues if your frm = "xxxx#xxxxxx.com" or to = "xxxx#xxxxxx.com" constains unicode characters. You can't use Header there.
I solved it, the solution is this:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
frm = "xxxx#xxxxxx.com"
msg = MIMEMultipart('alternative')
msg.set_charset('utf8')
msg['FROM'] = frm
bodyStr = ''
to = "xxxx#xxxxxx.com"
#This solved the problem with the encode on the subject.
msg['Subject'] = Header(
body.getAttribute('subject').encode('utf-8'),
'UTF-8'
).encode()
msg['To'] = to
# And this on the body
_attach = MIMEText(bodyStr.encode('utf-8'), 'html', 'UTF-8')
msg.attach(_attach)
server.sendmail(frm, to, msg.as_string())
server.quit()
Hope this helps!
Thanks!
I found a very easy workaround here on (https://bugs.python.org/issue25736):
msg = '''your message with umlauts and characters here : <<|""<<>> ->ÄÄ">ÖÖÄÅ"#¤<%&<€€€'''
server.sendmail(mailfrom, rcptto, msg.encode("utf8"))
server.quit()
So, to encode those unicode characters the right way, add
msg.encode("utf8")
at the end of the sendmail command.