I'm trying to send out some mails from the console on my production server, and they're not going out. I can't work out why. I have just your standard email setup with sendmail. When I call the Mailer.deliver_ method I get this back:
#<TMail::Mail port=#<TMail::StringPort:id=0x3fe1c205dbcc> bodyport=#<TMail::StringPort:id=0x3fe1c2059e00>>
Added some more info:
So, for example, I have this line in my controller when a new user signs up, to send them a "welcome" email:
Mailer.deliver_signup(#user, request.host_with_port, params[:user][:password])
This works fine. I thought that I should be able to do the same thing from the console, eg
user = User.find(1)
Mailer.deliver_signup(user, "mydomainname.example", "password")
When I do this, I get the Tmail::StringPort object back, but the mail appears to not get sent out (i'm trying to send emails to myself to test this).
I'm on an Ubuntu server in case that helps. thanks - max
Quicker version:
ActionMailer::Base.mail(
from: "test#example.co",
to: "valid.recipient#domain.example",
subject: "Test",
body: "Test"
).deliver_now
I ran into a similar problem this morning on a Rails 3 app where I called:
UserMailer.activation_instructions(#user)
This gave me the data but did not send the e-mail out. To send, I called:
UserMailer.activation_instructions(#user).deliver
This did the trick. Hopefully this might work for you too!
For Sending email from Rails Console first we have to execute this setting in console for action mailer settings.
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
domain: 'gmail.com',
authentication: 'plain',
enable_starttls_auto: true,
user_name: 'your#gmail.com',
password: 'yourpassword'
}
After that If we execute email sending code it will deliver email.
UserMailer.activation_instructions(#user).deliver_now
if you want to send attachments
mailer = ActionMailer::Base.new
mailer.attachments["file.jpg"] = File.read("/dir/file.jpg")
mailer.attachments["file.txt"] = "some text"
mailer.mail(from: "me#example.com",
to: "you#example.com",
subject: "Email with attachments",
body: "included the documents below\n\n")
mailer.message.deliver
mail has to come after the attachments, because it creates the headers.
I am not 100% if I understand what you are trying to do.
If you try to send out e-mails to the Internet, your sendmail must be configured in a way to forward those e-mails to the proper e-mails server. Depending on which Ubuntu release you use you can just reconfigure the package to do this.
You also might think if you want to use procmail instead of sendmail.
You can reconfigure the e-mail configuration with
dpkg-reconfigure sendmail
of use procmail instead if you use that package. The configuration dialogue gives you some option where you can configure it to forward all mail to the appropriate e-mail server. However, you need to think if you need authentication or if that server just accepts e-mails from your server.
Related
I currently have Rails applications that use SES to send emails. Unfortunately no matter how much code I put in my application I still get emails with invalid email addresses.
I want to use AWS to verify if I have a valid email address, meaning that the syntax is correct and does other verification like checking if the mailbox exists.
I installed the aws-sdk-rails gem in my application. I added my access_key_id and secret_access_key to config/credentials.yml.enc.
I added the following code from this awsdocs/aws-doc-sdk-examples GitHub repository to my contact form and made minor changes.
require 'aws-sdk-ses'
# Replace recipient#example.com with a "To" address.
recipient = params[:email]
error = " "
# Create a new SES resource in the us-west-2 region.
# Replace us-west-2 with the AWS Region you're using for Amazon SES.
ses = Aws::SES::Client.new(region: 'us-west-2')
# Try to verify email address.
begin
ses.verify_email_identity({
email_address: recipient
})
puts 'Email sent to ' + recipient
# If something goes wrong, display an error message.
rescue Aws::SES::Errors::ServiceError => error
puts "Email not sent. Error message: #{error}"
end
I entered an email address that AWS SES said that the mailbox didn't exist this morning. However when I ran this code it didn't produce an error as I thought it might. When I checked the Rails debug log error was blank. The region in my code is the one that I use to successfully send transactional emails from all my websites.
I couldn't find any documentation about that code that says how much verification it does for the email address.
Can I use this gem to find if email addresses exist or have other problems like SES checks when an email has a To: email address?
I have implemented a platform using rails, and the goal is to send thousands of emails to customers with one click. The concept is that an email array runs each loop and inside each loop runs send email functionality like below.
#emails = ['abc#gmai.com', 'abc#example.com'] # More than 3 thousands
#emails.each do |email|
aws_email_sender(email, #email_subject, #email_body_html)
end
And the email function is like below:
def aws_email_sender(recipient, subject, htmlbody)
sender = "hello#example.com"
awsregion = "ap-west-1"
# The HTML body of the email.
htmlbodycontent = "#{htmlbody}"
# The email body for recipients with non-HTML email clients.
textbody = "This email was sent with Amazon SES using the AWS SDK for Ruby."
# Specify the text encoding scheme.
encoding = "UTF-8"
# Create a new SES resource and specify a region
ses = Aws::SES::Client.new(region: awsregion)
# Try to send the email.
begin
# Provide the contents of the email.
resp = ses.send_email({
destination: {
to_addresses: [recipient]
},
message: {
body: {
html: {
charset: encoding,
data: htmlbodycontent
},
text: {
charset: encoding,
data: textbody,
},
},
subject: {
charset: encoding,
data: subject,
},
},
source: sender,
});
# If something goes wrong, display an error message.
rescue Aws::SES::Errors::ServiceError => error
puts "Email not sent. Error message: #{error}"
end
end
The email is sending well by AWS but my rails application has gone down like
A timeout occurred, error code 524
I couldn't get the breaking point, why has my application gone down every time?
Thanks in Advance
If 524 is an HTTP status code then it means...
Cloudflare was able to make a TCP connection to the website behind them, but it did not reply with an HTTP response before the connection timed out.
Meaning your Rails app is behind a Cloudflare proxy. Cloudflare received an HTTP request, forwarded it to your app, waited around for your app to respond, but your app never did. A more detailed explanation can be found here.
Probably because it's trying to send emails to 3000 people one-by-one.
There's two strategies to fix this.
Use Bulk Email
Since the content of the email is the same for everyone, use an email template to send bulk email using the #send_bulk_templated_email method.
You can send to up to 50 addresses at a time, so use #each_slice to loop through emails in slices of 50.
This will be more efficient, but your app will still be waiting around for 3000/50 = 60 AWS API calls. At worst it will still time out. At best the user will be waiting around for a form submission.
Use A Background Job
Anytime your app needs to do something that might take a lot of time, like using a service or a large database query, consider putting it into a background job. The Rails app queues up a job to send the emails, and then it can respond to the web request while the mailing is handled in the background. This has other advantages: errors calling the service won't cause an error for the user, and failed jobs due to a temporary service outage can automatically be retried.
In Rails this is done with ActiveJob and you could write a job class to send your mail.
Use ActionMailer
However, Rails also offers a class specifically for sending email in the background: ActionMailer. You can have ActionMailer use AWS with the aws-sdk-rails gem.
config.action_mailer.delivery_method = :ses
I have Mailgun set up to forward emails to my /rails/action_mailbox/mailgun/inbound_emails/mime endpoint.
When my endpoint receives the request, it gives the following error:
ArgumentError (Missing required Mailgun API key. Set
action_mailbox.mailgun_api_key in your application's encrypted
credentials or provide the MAILGUN_INGRESS_API_KEY environment
variable.)
However, MAILGUN_INGRESS_API_KEY is in fact set. When I run ENV["MAILGUN_INGRESS_API_KEY"] in the console, I see my API key. I even pasted in the API key determination code from GitHub to see if there was a problem there, but the return value I got was my actual API key.
Any ideas on what the problem could be?
Just checking few things to see if can rectify, as I understand you know much better than me about rails.
Do you have setup mailgun api_key in environment configuration like for development config/environments/development.rb
config.action_mailer.delivery_method = :mailgun
config.action_mailer.mailgun_settings = {
api_key: ENV['MAILGUN_INGRESS_API_KEY'],
domain: 'your_domain.com',
# api_host: 'api.eu.mailgun.net' # Uncomment this line for EU region domains
}
Now let us do one test, visit (bin.mailgun.net) and get paste bin url then run rails c
mg_client = Mailgun::Client.new(ENV["MAILGUN_INGRESS_API_KEY"], "bin.mailgun.net", "aecf68de_you_got_visiting_site", ssl = false)
message_params = { from: 'bob#sending_domain.com',
to: 'sally#example.com',
subject: 'The Ruby SDK is awesome!',
text: 'It is really easy to send a message!'
}
result = mg_client.send_message("your_sending_setup_on_mailgun_domain.com", message_params)
puts result.inspect
See what message came and you may get idea. There could be environment configuration issue also for development you have to setup different then for production. Also check on paste-bin does it got any hit.
I am building a form in C#, .NET, and MVC. On the back end the form will send its contents over email. For testing, I am using a local install of hMailServer.
Initially I set HMS to run as localhost.localdomain; the SMTP setting for "local host name" is localhost. I attempted to connect to it on port 587, like so:
SmtpClient smtp = new SmtpClient
{
Host = WebConfigurationManager.AppSettings["emailServer"],
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = true,
Credentials = networkCredential
};
I have double- and triple-checked that the credentials are the mail server user and password that I set. Here they are, in case this helps:
<add key="emailUser" value="user#localhost.localdomain"/>
<add key="emailPassword" value="~~~"/>
<add key="emailServer" value="localhost.localdomain"/>
When using localhost.localdomain, sending mail throws an exception, with the outer message: "Failure sending mail", and the inner message: "The remote name could not be resolved: 'localhost.localdomain'."
So I tried using companyname.com. Sending mail throws an exception, with the outer message: "Failure sending mail", and the inner message: "Unable to connect to the remote server."
I expect either my HMS domain config is wrong or my protocol config is wrong. The HMS documentation didn't help me, but I may not have known what to look for.
ETA
hMail server status shows zero processed messages in a week, despite all my testing.
Here is how I configured it for development:
Created host file entry like following:
local.myname.com 127.0.0.1
Once done, I opened command prompt and make sure it is updated. I tested it by following:
tracert local.myname.com
It should return 127.0.0.1 if host file entry is updated.
Next, in hmail, we need to create a new domain: local.myname.com and add an email address with password. so your email address would be something like admin#local.myname.com.
Next is, in advance you need to double check the protocols configuration and IP range vs authentication configuration as well.
In my case I configured to block external incoming and outgoing emails and skipped authentication for internal emails. So basically that;s what you can do in advance - IP range configuration. Then with the development, you just need to make sure all your emails are *#local.myname.com and it should work.
Also enable logging in hmail to get detailed error that can help solve the problem because hmail's help documentation works directly with their error codes nicely.
hMail is actually good choice for real emails. For development, I would recommend using smtp4dev though.
I`m trying to create the following feature: You register and receive an email like vouldjeff+ewr#myapp.com and when you send something to this email it automatically appears in something like your wall... So my problem is how to realize the creation of the email and the receiving of the mail itself.
Any ideas?
Ruby provides Net/IMAP and Net/POP3 you can use to login into your email account.
Here's a small tutorial.
POP3
pop = Net::POP3.new("pop.gmail.com", port)
pop.enable_ssl
pop.start('YourAccount', 'YourPassword')
if pop.mails.empty?
puts 'No mail.'
else
i = 0
pop.each_mail do |m|
File.open("inbox/#{i}", 'w') do |f|
f.write m.pop
end
m.delete
i += 1
end
puts "#{pop.mails.size} mails popped."
end
pop.finish
IMAP
imap = Net::IMAP.new('imap.gmail.com')
imap.authenticate('LOGIN', 'username', 'password')
imap.select('INBOX')
imap.search(['ALL']).each do |message_id|
msg = imap.fetch(message_id,'RFC822')[0].attr['RFC822']
MailReader.receive(msg)
imap.store(message_id, "+FLAGS", [:Deleted])
end
imap.expunge()
There might be other options but that's how we do it:
Postfix
Rails Cron Job
Postfix allows you to specify a MySQL table/view to check whether an email address exists or not. You can also define Mail Forwardings.
Create a DB View to match the requirements on Postfix
This View should contain all the email addresses and forward them to a different mail account, like mailparser.
Now your Rails can either
use a POP3/IMAP frontend to the mailserver (you should install Dovecot or Courier then) to fetch the mails and process them
or go to the place on the disk where all the mails are located (check Postfix config for that) and parse the files as TMail objects and process them.
A different option is to make Postfix call script/runner with the Mail data, but rails boot-up can take long and a lot of memory, so I prefer having a Cronjob/Backgroundjob/Worker to do this.
P.S. The Creation of the E-Mail will be done by creating a Model for your Rails app which the View will use as a basis.
Sending E-Mails is simple as pie. Simply have a look at the ActionMailer Basics. If you also want to receive E-Mail, you should write a daemon that fetches Mails from the mailserver continuously in the background.
Here a snippet that fetches Mails via POP:
require 'net/pop'
config = {
:host => "mail.example.com",
:user => "foobar#example.com",
:password => "…",
:port => 110,
:timeout => 10
}
pop = Net::POP3.new(config[:host])
pop.start(config[:user], config[:password])
if pop.mails.empty?
puts "No mails…"
else
pop.mails.each do |mail|
# do stuff with mail
end
end
This is pure Ruby-Code, Rails is not needed for this snippet.