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.
Related
I'm getting this error using the common EmailSender service with email address like test#pläne.de:
An unhandled exception occurred while processing the request.
SmtpException: Mailbox unavailable. The server response was: Requested action not taken: mailbox unavailable
System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, string response)
I tried with IdnMapping etc. but had no success. Has anybody had a similar issue and found a solution?
Code snippet:
public Task SendEmailAsync(string email, string subject, string htmlMessage)
{
var smtp = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("Smtp");
string fromMail = smtp["FromAddress"];
string fromPassword = smtp["Password"];
// string userName = smtp["UserName"];
MailMessage message = new MailMessage();
// idn mapping
IdnMapping idn = new IdnMapping();
message.From = new MailAddress(fromMail);
// message.From = new MailAddress(idn.GetAscii(fromMail));
message.Subject = subject;
message.To.Add(new MailAddress(email));
message.Body = "<html><body> " + htmlMessage + " </body></html>";
message.IsBodyHtml = true;
var smtpClient = new SmtpClient(smtp["Server"])
{
Port = Convert.ToInt32(smtp["Port"]),
//Credentials = new NetworkCredential(userName, fromPassword),
Credentials = new NetworkCredential(fromMail, fromPassword),
//Credentials = new NetworkCredential(idn.GetAscii(fromMail), fromPassword),
EnableSsl = true,
};
return smtpClient.SendMailAsync(message);
}
Thanks!
umlauts ä ü ö is an invalid character. And there doesn't seem to be a ready-made solution to this problem.
You can create some sort of translation table, for example:
ö = oe
ä = ae
ü = ue
Maybe this will help you solve the problem.
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)
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()
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()
I am trying to send an html formatted email using SendMail() in PeopleCode. What I am trying to do is very a basic html email (e.g. bolded text, a href tags, etc).
We recently upgraded to PeopleTools 8.52
When I use the default SendMail() example from PeopleBooks, The email is sent as plain text, regardless of the fact that I specified the content type as "text/html".
Local string &MAIL_CC, &MAIL_TO, &MAIL_BCC, &MAIL_SUBJECT, &MAIL_TITLES, &MAIL_TEXT, &MAIL_FILES, &MAIL_FROM, &REPLYTO, &SENDER;
Local number &MAIL_FLAGS;
&MAIL_FLAGS = 0;
&MAIL_TO = "laurie_thomas#peoplesoft.com";
&MAIL_CC = "";
&MAIL_BCC = "";
&MAIL_SUBJECT = "Testing SendMail - Are you receiving Attachment?";
&MAIL_TEXT = "This is a test for SendMail function";
&MAIL_FILES = "/data9/ps/e841g2bp/lat/attach.txt";
&MAIL_TITLES = "";
&MAIL_FROM = "peoplesoft#peoplesoft.com";
&MAIL_SEP = ";";
&CONTTYPE = "Content-type: text/html; charset=utf8";
&REPLYTO = "lthomas#peoplesoft.com";
&SENDER = "00972#peoplesoft.com";
&RET = SendMail(&MAIL_FLAGS, &MAIL_TO, &MAIL_CC, &MAIL_BCC, &MAIL_SUBJECT, &MAIL_TEXT, &MAIL_FILES, &MAIL_TITLES, &MAIL_FROM, &MAIL_SEP, &CONTTYPE, &REPLYTO,&SENDER);
If &RET <> 0 Then
MessageBox(0, "", 0, 0, "Return code from SendMail=" | &RET);
End-If;
As it turns out, this is a documented bug observed by Oracle (Bug:13714374). This occurs when upgrading from PeopleTools 8.51 to 8.52 (which is why it happened to us).
Solution from Oracle:
This Bug Fixed in the PT 8.52.08 patch, which became available on
05/24/2012