How to setup send HTML email with mail gem? - html

I am sending email using the Mail gem. Here's my code:
require 'mail'
require 'net/smtp'
Mail.defaults do
delivery_method :smtp, { :address => "smtp.arrakis.es",
:port => 587,
:domain => 'webmail.arrakis.com',
:user_name => 'myname#domain.com',
:password => 'pass',
:authentication => 'plain',
:enable_starttls_auto => true }
end
Mail::ContentTypeField.new("text/html") #this doesnt work
msgstr= File.read('text2.txt')
list.each do |entity|
begin
Mail.deliver do
from 'myname#domain.com'
to "#{entity}"
subject 'a good subject'
body msgstr
end
rescue => e
end
end
end
I don't know how to set up the content type, so that I can format my email as html for example. Though I actually just wish to be able to define bold text like my email client does: bold text. Does anybody know which content-type I need to specify in order to achieve this, and how to implement it with mail?
Just a note, the code above works fine for sending plain text email.

From the documentation
Writing and sending a multipart/alternative (html and text) email
Mail makes some basic assumptions and makes doing the common thing as
simple as possible.... (asking a lot from a mail library)
mail = Mail.deliver do
to 'nicolas#test.lindsaar.net.au'
from 'Mikel Lindsaar <mikel#test.lindsaar.net.au>'
subject 'First multipart email sent with Mail'
text_part do
body 'This is plain text'
end
html_part do
content_type 'text/html; charset=UTF-8'
body '<h1>This is HTML</h1>'
end
end

#Simone Carletti's answer is essentially correct, but I was struggling with this and didn't want a plain text portion to my email and a separate HTML portion. If you just want the entire email to be HTML, something like this will work:
mail = Mail.deliver do
to 'nicolas#test.lindsaar.net.au'
from 'Mikel Lindsaar <mikel#test.lindsaar.net.au>'
subject 'First email sent with Mail'
content_type 'text/html; charset=UTF-8'
body '<h1>This is HTML</h1>'
end
I may have missed it, I didn't see anything in the Mail gem documentation describing how to do that, which I would think would be more common than making a multipart message. The documentation only seems to cover plain text messages and multipart messages.

Related

Django email message as HTML

I have an email template that I use to send emails of different kinds. I'd rather not keep multiple email HTML templates, so the best way to handle this is to customize the message contents. Like so:
def email_form(request):
html_message = loader.render_to_string(
'register/email-template.html',
{
'hero': 'email_hero.png',
'message': 'We\'ll be contacting you shortly! If you have any questions, you can contact us at meow#something.com',
'from_email': 'lala#lala.com',
}
)
email_subject = 'Thank you for your beeswax!'
to_list = 'johndoe#whatever.com'
send_mail(email_subject, 'message', 'from_email', [to_list], fail_silently=False, html_message=html_message)
return
When the email is sent however, the html codes don't work. The message appears as it is exactly, angled brackets and all. Is there a way for me to force it to render as HTML tags?
Use EmailMessage to do it with less trouble:
First import EmailMessage:
from django.core.mail import EmailMessage
Then use this code to send html email:
email_body = """\
<html>
<head></head>
<body>
<h2>%s</h2>
<p>%s</p>
<h5>%s</h5>
</body>
</html>
""" % (user, message, email)
email = EmailMessage('A new mail!', email_body, to=['someEmail#gmail.com'])
email.content_subtype = "html" # this is the crucial part
email.send()
Solved it. Not very elegant, but it does work. In case anyone's curious, the variable placed in the email template should be implemented as so:
{{ your_variable|safe|escape }}
Then it works! Thanks guys!
You can use EmailMultiAlternatives feature present in django instead of sending mail using send mail. Your code should look like the below snipet.
from django.core.mail import EmailMultiAlternatives
def email_form(request):
html_message = loader.render_to_string(
'register/email-template.html',
{
'hero': 'email_hero.png',
'message': 'We\'ll be contacting you shortly! If you have any questions, you can contact us at meow#something.com',
'from_email': 'lala#lala.com',
}
)
email_subject = 'Thank you for your beeswax!'
to_list = 'johndoe#whatever.com'
mail = EmailMultiAlternatives(
email_subject, 'This is message', 'from_email', [to_list])
mail.attach_alternative(html_message, "text/html")
try:
mail.send()
except:
logger.error("Unable to send mail.")

Send a plain text email with an embedded <a> tag in mailgun

I am trying to embed an <a> link within the text of an email I'm sending through mailgun. What is the correct syntax?
RestClient.post "https://api:#{ENV['MAILGUN_SECRET']}"\
"#api.mailgun.net/v3/#{ENV['MAILGUN_DOMAIN']}/messages",
:from => "Mailgun <mailgun##{ENV['MAILGUN_DOMAIN']}>",
:to => "#{#lead.email}",
:subject => "Test",
:text => "Here is the message, here(http://www.foo.com) is the link"
I dont think that you can send a "text" email with HTML you have to pick one
I like to send all my emails a HTML
This is how my mailer looks like:
class SomeMailer < ActionMailer::Base
def email_method(post_id, lead_id)
#post = Post.find(post_id)
#lead = Lead.find(lead_id)
mail(
:from => "Email Sender<info#example.com>",
:to => #lead.email,
:reply_to => 'Email Sender<info#example.com>',
:subject => "Test"
)
end
end
now this is the fun part. Create a folder called SomeMailer in app/views so you end up with app/views/some_mailer
now create a file in that directory called email_method.html.erb that contains your html like:
Here is the message, here( foo.com ) is the link
I hope that this helps

How do you get Amazon SES to send upon submission of form in Padrino

Following the instructions here: http://www.padrinorb.com/guides/padrino-mailer
I have the delivery method added on the app.rb file:
class OscarAffiliate < Padrino::Application
register Padrino::Rendering
register Padrino::Mailer
register Padrino::Helpers
enable :sessions
set :delivery_method, :smtp => {
:address => "email-smtp.us-east-1.amazonaws.com",
:port => 587,
:user_name => 'AKIAIQ5YXCWFKFXFFRZA',
:password => 'AqMNMFecKSYR/TRu8kJgocysAL5SmIUsu2i8u/KAfeF/',
:authentication => :plain,
:enable_starttls_auto => true
}
But via the generation through Padrino and the Mailer generation, I do not have the recommended "sessions" controller in which this should belong:
post :create do
email(:from => "tony#reyes.com", :to => "john#smith.com", :subject => "Welcome!", :body=>"Body")
end
Am I missing something?
I have the form for a basic data collection at an office and just need an email to be sent to 5 recipients with all the form fields in the message body.
Thanks
It appears to me that you're trying to email a person (or multiple people) after a form is submitted. Possibly you're saving information from that form to a database. I think that you are a little confused on how to use Padrino mailers. Allow me to clarify: In order to send an email, using Padrino's mailer functionality, with a full body of content, you must create a Padrino Mailer (I've outlined this below). Then you must configure that mailer so that you may pass variables to it when you call it. Those variables can then be used in the view, which your mailer renders into the email body before sending the email. This is one way of accomplishing what it appears you are trying to do and it is probably the most straight-forward. You can find more information about this procedd under "Mailer Usage" on the help page you provided in your question. I've outlined an example usage, tailored to what I believe your needs are, below.
Instructions
I threw together this code sample and tested it against my AWS account; it should work in production.
In your app/app.rb file, include the following (you have already done so):
set :delivery_method, :smtp => {
:address => 'email-smtp.us-east-1.amazonaws.com',
:port => 587,
:user_name => 'SMTP_KEY_HERE',
:password => 'SMTP_SECRET_HERE',
:authentication => :plain,
:enable_starttls_auto => true
}
Then create a Mailer in app/mailers/affiliate.rb:
# Defines the mailer
DemoPadrinoMailer.mailer :affiliate do
# Action in the mailer that sends the email. The "do" part passes the data you included in the call from your controller to your mailer.
email :send_email do |name, email|
# The from address coinciding with the registered/authorized from address used on SES
from 'your-aws-sender-email#yoursite.com'
# Send the email to this person
to 'recipient-email#yoursite.com'
# Subject of the email
subject 'Affiliate email'
# This passes the data you passed to the mailer into the view
locals :name => name, :email => email
# This is the view to use to redner the email, found at app/views/mailers/affiliate/send_email.erb
render 'affiliate/send_email'
end
end
The Affiliate Mailer's send_email view should be located in app/view/mailers/affiliate/send_email.erb and look like this:
Name: <%= name %>
Email: <%= email %>
Finally, you can call your mailer from inside whatever method (and controller) you're accepting form submissions from. Be sure to replace the strings with actual form data. In this example, I used a POSTed create action, which did not save any data (thus the strings with fake data):
post :create do
# Deliver the email, pass the data in after everything else; here I pass in strings instead of something that was being saved to the database
deliver(:affiliate , :send_email, "John Doe", "john.doe#example.com")
end
I sincerely hope that this helps you in your journey with Padrino, and welcome to the Stack Overflow community!
Sincerely,
Robert Klubenspies

Issue with RoR ActionMailer --cannot send plaintext and HTML emails simultaneously.

I'm having an issue with my Rails application--I'm having trouble sending both a HTML and plaintext version of my email. NOTE: the email does send; however, it's not styled correctly... there is a link to the results below.
It's recommended everywhere that if you want to send HTML you should also send a plain text alternative too. Unfortunately, it appears that I'm doing something wrong, as my application does not allow me to send both HTML and plaintext, without the HTML looking very weird.
here is my mailer model:
class ProjectMembersMailer < ActionMailer::Base
def membership_invitation(membership)
#project = membership.project
#user = membership.user
mail( :subject => %(Invitation to join project #{#project.business_name}),
:from => %("App" <no-reply#appname.com>),
:to => #user.account.email,
:content_type => "text/html" ) do |format|
format.html
format.text
end
end
end
My project_member_mailer views have two files: membership_invitation.html.haml and membership_invitation.text.erb (please note that the second file is using .erb, but even if I convert it to a .haml extension for consistency I get the same error)
Here is picture of that the output looks like when I attempt to send it using the code above. Please note that I removed some of the text.
Basically it looks like it's sending the text version above the html version of the file. Is there an alternate way to sending both plaintext and HTML emails without this happening? Or am I missing something--like, should these emails not be sent simultaneously? Any help would be greatly appreciated. Thank you so much for your time and help!
According to the Action Mailer Rails Guide you do not need to use the "format" method, and should remove the "content-type" parameter too.
mail will automatically detect that there are both html and text templates and will automatically create the email as multipart/alternative
Just try:
mail( :subject => %(Invitation to join project #{#project.business_name}),
:from => %("App" <no-reply#appname.com>),
:to => #user.account.email)
I had the exact same problem, and it can be fixed with just one simple thing. Place format.text over format.html
def membership_invitation(membership)
#project = membership.project
#user = membership.user
mail( :subject => %(Invitation to join project #{#project.business_name}),
:from => %("App" <no-reply#appname.com>),
:to => #user.account.email,
:content_type => "text/html" ) do |format|
format.text
format.html
end
end

How to format email for gmail?

I wrapped the email's body in <html><body><pre>. Show original in gmail gives me actually how I want the email to be formatted:
Mime-Version: 1.0
Content-Type: text/html;
charset=UTF-8
Content-Transfer-Encoding: 7bit
Ant run name : Basics of Edumate
Overall result : pass
Ant run took: 4 minutes 15 seconds
--------------------------
Details for all test suits
--------------------------
login : Pass
AddCycleTemplate: Pass
AddCycleTemplate: Pass
AddAcademicYear : Pass
AddAcademicYear : Pass
But the actual email is displayed as one line. Note that space that I use to align : is somehow omitted as well as new lines.
Ant run name : Basics of Edumate Overall result : pass Ant run took: 4 minutes 15 seconds -------------------------- Details for all test suits -------------------------- login : Pass AddCycleTemplate: Pass AddCycleTemplate: Pass AddAcademicYear : Pass AddAcademicYear : Pass
I send the email from ruby using pony.
Any suggestions how to get the formatting inside gmail as desired?
I would recommend to simply use an HTML table to do that.
Just for the sake of answering thoroughly, the code would be something like:
<table>
<tr>
<td>Mime-Version:</td>
<td>1.0</td>
</tr>
<tr>
<td>Content-Type:</td>
<td>text/html;</td>
</tr>
...
</table>
etc..
I think using <br/> for line breaks would work, but there's probably a better solution...
This the was I send html email to gmail. I guess what I was missing was :html_body => body, part of pony's settings.
def email_it(body, subject,to,from)
$smtp = 'mail.com.au'
$smtp_port = 25
Pony.mail(
:to => to,
:from => from,
:subject => subject,
:body => Nokogiri::HTML(body).text,
:html_body => body,
:via => :smtp,
:via_options => {
:address => $smtp,
:port => $smtp_port,
:enable_starttls_auto => false
}
)
end