Can't Send Email With Network.Mail.SMTP - email

I've been reading through the documentation for Network.Mail.SMTP to send an e-mail. My problem comes after the code begins to run I get a message saying
socket 11: Data.ByteString.hGetLine end of file
When I check the inbox folder for the recipient's email and the sent folder of the sending email, there is no message being sent. What can I do to make this code do it's job. I've posted the code and omitted some of the sensitive sections.
import Network.Mail.Mime
import Network.Mail.SMTP
import qualified Data.Text as T
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
mFrom = Address (Just $ T.pack "FirstName LastName") (T.pack "Sender's Email")
mTo = [Address Nothing (T.pack "Recipient Email")]
mCC = []
mBCC = []
mHeader = [(B.empty, (T.pack "Test Header"))]
pType = T.empty
pEncoding = None
pFilename = Nothing
pHeader = [(B.empty, T.pack "Test Part Header")]
pContent = BL.empty
pPart = Part pType pEncoding pFilename pHeader pContent
alternative =[pPart]
mParts = [alternative]
mMail = Mail mFrom mTo mCC mBCC mHeader mParts
a = sendMailWithLogin' "smtp.gmail.com" 465 "Sender Email" "Sender Password" mMail
main = a

I could reproduce the error, but honestly I don't know why this is happening, maybe it has to do with encryption, which I guess google forbids not to have (but that is just a guess).
But since I remembered having sent some email with haskell in the past - I dug out some old code: note this uses HaskellNet
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Monad (when)
import Control.Exception (bracket)
import Network.HaskellNet.SMTP.SSL
main :: IO ()
main = bracket
(connectSMTPSSL "smtp.gmail.com")
closeSMTP $ \conn ->
do success <- authenticate LOGIN
"myemailaddress#gmail.com"
"password"
conn
when success
$ sendPlainTextMail "to" "from" "Test" "test" conn
the usage is pretty straightforward establish a connection, authenticate over it send your email, if you have attachments use sendMimeMail or sendMimeMail' or if you want to use the existing Mail type you already built use sendMimeMail2.
If you haven't seen bracket it is the (quite elegant) haskell variant of try..finally - it simply makes sure that the connection is closed.

Related

How to control tracking options and tags when using Mailgun's SMTP option (i.e. not using their API)

I’m using python to send emails using Mailgun’s SMTP server. I wish to use Mailgun’s builtin ability to tag my messages, and to track open and click events.
I know this can be done using Mailgun’s send message API, by adding headers like o:tag, o:tracking, o:tracking-clicks and o:tracking-opens (as explained here: https://documentation.mailgun.com/en/latest/api-sending.html#sending)
However, seeing as I'm the SMTP gateway and not the API, I’m trying to understand how to achieve the same result - emails that are tagged and fully tracked in Mailgun.
Any thoughts on how it can be done?
This is my little script at the moment:
message = MIMEMultipart("alternative")
message["Subject"] = "This is an email"
message["From"] = “<from email>”
message["To"] = “<to email>”
htmlpart = MIMEText("<html><body>email here!</body></html>", "html")
message.attach(htmlpart)
server = smtplib.SMTP_SSL(“<smtp server>”, 465)
server.ehlo()
server.login(“<username>”, “<password>”)
server.sendmail(from_addr=“<from email>”, to_addrs=“<to email>”, msg=message.as_string())
server.close()
Found it!
The following X-Mailgun headers can be added:
https://documentation.mailgun.com/en/latest/user_manual.html#sending-via-smtp
So my script would be:
message = MIMEMultipart("alternative")
message["Subject"] = "This is an email"
message["From"] = “<from email>”
message["To"] = “<to email>”
message["X-Mailgun-Tag"] = "<tag>"
message["X-Mailgun-Track"] = "yes"
message["X-Mailgun-Track-Clicks"] = "yes"
message["X-Mailgun-Track-Opens"] = "yes"
htmlpart = MIMEText("<html><body>email here!</body></html>", "html")
message.attach(htmlpart)
server = smtplib.SMTP_SSL(“<smtp server>”, 465)
server.ehlo()
server.login(“<username>”, “<password>”)
server.sendmail(from_addr=“<from email>”, to_addrs=“<to email>”, msg=message.as_string())
server.close()
Now my email is tagged (can be analysed on a tag level in Mailgun), and clicks are tracked.
Happy days!

Flask Mail - Style some phrases

I'm sending e-mails using Flask Mail, but for now, after reading the documentation, I didn't see how I cant format my text.
So my question is:
- Am I able to format the text? Such as using italic, bold, or even using a different font.
If possible, where how can I modify to add this functionality?
from flask import Flask
from flask_mail import Mail, Message
import os
app = Flask(__name__)
mail_settings = {
"MAIL_SERVER": 'smtp.gmail.com',
"MAIL_PORT": 465,
"MAIL_USE_TLS": False,
"MAIL_USE_SSL": True,
"MAIL_USERNAME": os.environ['EMAIL_USER'],
"MAIL_PASSWORD": os.environ['EMAIL_PASSWORD']
}
app.config.update(mail_settings)
mail = Mail(app)
if __name__ == '__main__':
with app.app_context():
msg = Message(subject="Test subject",
sender=app.config.get("MAIL_USERNAME"),
recipients=["<testacc#gmail.com>"],
body="test email\nBest regards\n\nJohn Doe")
mail.send(msg)
You can include HTML in you message like so
msg.html = "<b>testing</b>"
or render prepared template
msg = Message(subject="Test subject",
sender=app.config.get("MAIL_USERNAME"),
recipients=["<testacc#gmail.com>"])
msg.html = render_template('emails/your_template.html')
mail.send(msg)
take a look here

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()

Python 3.4 email to multiple receivers throws an ERROR

I'm writing a script to send an email to more than one email account, but not able, yet.
It works as it is below, but if I set receivers='xxx#xxx.com','yyy#yyy.com' it won't work, it throws an error:
AttributeError: 'tuple' object has no attribute 'encode'.
How can I set receivers=?
def send_email (out_file):
sender = 'xxx#xxx.com'
receivers = 'xxx#xxx.com'
email_pass = 'aaaa'
filematch=re.findall('NE.*\.txt',out_file.name)
subject = ("NEXXXX_price_update")
message = ("The following file was forwarded to your ftp account %s " %filematch)
msg = 'Subject: %s\n%s' %(subject, message)
try:
smtpObj = smtplib.SMTP_SSL('smtp.gmail.com',0)
smtpObj.login(receivers, email_pass)
smtpObj.sendmail(sender, receivers, msg)
print ("Successfully sent email")
except SMTPException:
print ("email NOT successful")
print(SMTPException.__cause__)
smtpObj.quit()
You assign wrongly
receivers='xxx#xxx.com','yyy#yyy.com'
You suppose to assign as a tuple or list, not sure 100% which.
Give a try:
receivers=('xxx#xxx.com','yyy#yyy.com')
or
receivers=['xxx#xxx.com','yyy#yyy.com']

How to send e-mail with std.net.curl?

I tried to use example (with my login and pass) from http://dlang.org/phobos/std_net_curl.html#.SMTP
But every time I am getting error: std.net.curl.CurlException#std\net\curl.d(3691): Failed sending data to the peer on handle 7F6D08.
What's wrong? I tried to specify port (465) but it's not helped.
import std.net.curl;
// Send an email with SMTPS
auto smtp = SMTP("smtps://smtp.gmail.com");
smtp.setAuthentication("from.addr#gmail.com", "password");
smtp.mailTo = ["<to.addr#gmail.com>"];
smtp.mailFrom = "<from.addr#gmail.com>";
smtp.message = "Example Message";
smtp.perform();