Is there any way to use gmail as a smtp server on rails 2.3.5/ruby 1.9.1?
My smtp settings for actionmailer are
options = {
:address => "smtp.gmail.com",
:port => 587,
:domain => 'REMOVED',
:user_name => 'REMOVED',
:password => 'REMOVED',
:authentication => 'plain',
:enable_starttls_auto => true }
and these result in the error
Net::SMTPAuthenticationError: 530 5.7.0 Must issue a STARTTLS command first.
Try this:
#config/initializers/smtp_tls.rb
require "openssl"
require "net/smtp"
Net::SMTP.class_eval do
private
def do_start(helodomain, user, secret, authtype)
raise IOError, 'SMTP session already started' if #started
if RUBY_VERSION == "1.8.6"
check_auth_args user, secret, authtype if user or secret
else
check_auth_args user, secret if user or secret
end
sock = timeout(#open_timeout) { TCPSocket.open(#address, #port) }
#socket = Net::InternetMessageIO.new(sock)
#socket.read_timeout = 60 ##read_timeout
#socket.debug_output = STDERR ##debug_output
check_response(critical { recv_response() })
do_helo(helodomain)
raise 'openssl library not installed' unless defined?(OpenSSL)
starttls
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.sync_close = true
ssl.connect
#socket = Net::InternetMessageIO.new(ssl)
#socket.read_timeout = 60 ##read_timeout
#socket.debug_output = STDERR ##debug_output
do_helo(helodomain)
authenticate user, secret, authtype if user
#started = true
ensure
unless #started
# authentication failed, cancel connection.
#socket.close if not #started and #socket and not #socket.closed?
#socket = nil
end
end
def do_helo(helodomain)
begin
if #esmtp
ehlo helodomain
else
helo helodomain
end
rescue Net::ProtocolError
if #esmtp
#esmtp = false
#error_occured = false
retry
end
raise
end
end
def starttls
getok('STARTTLS')
end
def quit
begin
getok('QUIT')
rescue EOFError
end
end
Related
I attempted to send reset password email through a namecheap domain. I have reviewed every solution offered within StackOverflow and have not been able to get a viable solution. Let me know if I am missing any details below.
My Rails application is an API only.
It was working via gmail connection/smtp and when I switched it over to the namecheap/privateemail smtp it worked once.
After it worked locally I uploaded the code to heroku and that's when it started to fail.
# config/environments/development.rb
config.action_mailer.delivery_method = :sendmail
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default_options = {from: 'noreply#domainemail.com'}
config.action_mailer.default_url_options = { :host => '587'}
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'mail.privatemail.com',
port: 587,
domain: 'domainname.com',
user_name: ENV['EMAIL'],
password: ENV['EMAIL_PW'],
authentication: :plain,
enable_starttls_auto: true,
openssl_verify_mode: 'none',
ssl: true
}
Production:
config.cache_classes = true
config.action_mailer.delivery_method = :sendmail
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default_options = {from: 'noreply#domainname.com'}
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'mail.privatemail.com',
port: 587,
domain: 'domainname.com',
user_name: ENV['EMAIL'],
password: ENV['EMAIL_PW'],
authentication: :plain,
enable_starttls_auto: true,
openssl_verify_mode: 'none'
}
NotifierMailer class
class NotifierMailer < ApplicationMailer
default_url_options[:host] = ENV['BACKEND_URL']
default from: 'noreply#domainemail.com'
def create
admin = Admin.find_by(email: params[:email])
admin.generate_password_reset_token!
Notifier.password_reset(admin).deliver
end
def password_reset(admin)
#admin = admin
#url = "#{ENV['BACKEND_URL']}/password/reset?token=#{#admin.reset_password_token}&email=#{#admin.email}"
mail(to: "#{#admin.first_name} #{#admin.last_name} <#{#admin.email}>",
subject: "Ion Portal - Password Reset")
end
end
Password controller
class PasswordController < ApplicationController
protect_from_forgery with: :null_session
# include ActionController::RequestForgeryProtection
# protect_from_forgery with: :exception, unless: -> { request.format.json? }
def forgot
puts params
if params[:email].blank? # check if email is present
render json: {
error: "Email not present"
}
end
admin = Admin.find_by(email: params[:email]) # if present find admin by email
if admin.present?
admin.generate_password_token! #generate pass token
NotifierMailer.password_reset(admin).deliver_now
render json: { status: 'ok' }
else
render json: { error: ["Email address not found. Please check and try again."]}, status: :not_found
end
end
def reset
token = params[:token].to_s
if params[:email].blank?
return render json: {error: "Token not present"}
end
admin = Admin.find_by(reset_password_token: token)
if admin.present? && admin.password_token_valid?
if admin.reset_password!(params[:password])
redirect_to "#{ENV['ION_URL']}"
else
render json: {error: admin.errors.full_messages}, status: :unprocessable_entity
end
else
render json: { error: ["Link not valid or expired. Try generating a new link."]}, status: :not_found
end
end
def update
if !params[:password].present?
render json: {error: 'Password not present'}, status: :unprocessable_entity
return
end
if current_user.reset_password(params[:password])
render json: {status: 'ok'}, status: :ok
else
render json: {errors: current_user.errors.full_messages}, status: :unprocessable_entity
end
end
def successful_reset
render success_path
end
end
These settings worked for me. Turned out I also had left the settings for MailCatcher as well, that was my initial problem. Double check as well that what the domain setting and server address match, which in development, would mean setting the domain to 'localhost:3000'. Good luck!
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => 'mail.privateemail.com',
:port => 587,
:domain => 'localhost:3000',
:user_name => 'email#email.com',
:password => 'xxxxxxxxxxxxxxx',
:authentication => :plain,
:enable_starttls_auto => true,
}
After 24 hours of trial and error I had to remove a couple of lines of code to make it work.
config.action_mailer.smtp_settings = {
# For Gmail
# :address => "smtp.gmail.com",
# :port => "587",
# :domain => "gmail.com",
# :user_name => "noreply#gmail.com",
# :password => "pasword!",
# :authentication => "plain",
# :enable_starttls_auto => true
# For Namecheap
:enable_starttls_auto => true, #this is the important stuff!
:address => 'smtp.privateemail.com',
:port => 587,
:domain => 'privateemail.com',
:authentication => :plain,
:user_name => 'noreply#domainname.com',
:password => 'password!'
}
I removed the following:
enable_starttls_auto: true,
openss
l_verify_mode: 'none'
In order_mailer.rb:
default from: 'notifications#example.com'
def welcome_email(order)
#user = "Uday kumar das"
#url = 'http://example.com/login'
mail(to: 'dasudaykumar017#gmail.com', subject: 'Welcome to My Awesome Site')
end
In orders_conroller:
def delivery
#order1 = Order.where(:orderId=>params[:orderId])
#order = Order.find(#order1)
OrderMailer.welcome_email(#order).deliver
end
In environments/development.rb:
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
I am new to mails in rails.I am referring http://guides.rubyonrails.org/action_mailer_basics.html to learn. I am getting error like:
Net::SMTPAuthenticationError in OrdersController#delivery`
530-5.5.1 Authentication Required. Learn more at`
I did the same using my gmail, following are my configurations, try and see it if works
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
ActionMailer::Base.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:authentication => :plain,
:user_name => "<my gmail>#gmail.com",
:password => "<my gmail password>",
:openssl_verify_mode => 'none' }
Please note the:
:openssl_verify_mode => 'none'
section to skip the ssl errors
i try to configure redmine for email notifications
So my configuration in configuration.yml is :
production:
email_delivery:
delivery_method: :smtp
smtp_settings:
enable_starttls_auto: true
address: "smtp.gmail.com"
port: '587'
domain: "smtp.gmail.com"
authentication: :plain
user_name: "mymail#gmail.com"
password: "mypass"
According to this tutorial :
http://www.redmine.org/projects/redmine/wiki/EmailConfiguration#Simple-Login-Authentication-default-settings
But when i try : Send a test mail, i have this error :
An error occurred while sending mail (530 5.7.0 Must issue a STARTTLS command first. n7sm25368265eef.5 - gsmtp )
If i have :
production:
email_delivery:
delivery_method: :smtp
smtp_settings:
tls: true
enable_starttls_auto: true
address: "smtp.gmail.com"
port: '587'
domain: "smtp.gmail.com"
authentication: :plain
user_name: "mymail#gmail.com"
password: "mypass"
I have this error :
An error occurred while sending mail (SSL_connect returned=1 errno=0 state=unknown state: unknown protocol)
Any ideas ? Redmine version : 2.0.1, Ruby : 1.9.3
1.Save the following code within your rails app in lib/smtp_tls.rb:
require "openssl"
require "net/smtp"
Net::SMTP.class_eval do
private
def do_start(helodomain, user, secret, authtype)
raise IOError, 'SMTP session already started' if #started
check_auth_args user, secret, authtype if user or secret
sock = timeout(#open_timeout) { TCPSocket.open(#address, #port) }
#socket = Net::InternetMessageIO.new(sock)
#socket.read_timeout = 60 ##read_timeout
##socket.debug_output = STDERR ##debug_output
check_response(critical { recv_response() })
do_helo(helodomain)
if starttls
raise 'openssl library not installed' unless defined?(OpenSSL)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.sync_close = true
ssl.connect
#socket = Net::InternetMessageIO.new(ssl)
#socket.read_timeout = 60 ##read_timeout
##socket.debug_output = STDERR ##debug_output
do_helo(helodomain)
end
authenticate user, secret, authtype if user
#started = true
ensure
unless #started
# authentication failed, cancel connection.
#socket.close if not #started and #socket and not #socket.closed?
#socket = nil
end
end
def do_helo(helodomain)
begin
if #esmtp
ehlo helodomain
else
helo helodomain
end
rescue Net::ProtocolError
if #esmtp
#esmtp = false
#error_occured = false
retry
end
raise
end
end
def starttls
getok('STARTTLS') rescue return false
return true
end
def quit
begin
getok('QUIT')
rescue EOFError, OpenSSL::SSL::SSLError
end
end
end
2.Add this code to config/environment.rb (after everything else):
require “smtp_tls”
ActionMailer::Base.smtp_settings = {
:address => “smtp.gmail.com”,
:port => 587,
:authentication => :plain,
:user_name => “someone#openrain.com”,
:password => ’someonesPassword’
}
3.Use ActionMailer as normal.
I'm just about in the finishing stages of my website, however I am having trouble with the ActionMailer. It prints out the message just fine, I'm just eager to know how to wire it so it can send to gmail account. I'm primary confused how to route it and configure it properly. I have a contact page that has a model that takes parameters like the recipient, subject, message and the time it was sent: Mailer model: Note all this code is on a local machine
class UserEmail < ActionMailer::Base
default from: 'XXX#gmail.com'
def contact(sender, subject, message, sent_at = Time.now)
#sender = sender
#message = message
#sent_at = sent_at.strftime("%B %e, %Y at %H:%M")
mail(:subject => subject)
end
end
Here's the about controller which the contact methods lie in:
class AboutController < ApplicationController
# ...\controllers\home_controller.rb
#----------------------------------------------------
# show contact form
def contact
#title = "Contact"
#sender = ''
#subject = ''
#message = ''
end
def sendmail
#sender = params[:sender]
#subject = params[:subject]
#message = params[:message]
if validate(#sender, #subject, #message)
UserEmail.contact(#sender, #subject, #message).deliver
flash[:success] = "Your message sent sucessfully!"
redirect_to about_index_path
else
flash.now[:error] = "Your message did not send"
redirect_to about_index_path
end
end
private
def validate(sender, subject, message)
#email_regex = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
if sender.blank? || subject.blank? || message.blank?
#error = "Message not sent: Required information not filled"
return false
elsif subject.length >= 50
#error = "Message not sent: Subject must be smaller than 50 characters"
return false
elsif sender[#email_regex].nil?
#error = "Message not sent: Email not valid"
return false
else
return true
end
end
end
Now this is where I am lost.
Here's what my route like to the mailer. Is this routed appropriately?:
match '/contact_email', :to => 'about#sendmail'
When I configure the mailer, does the code rest in the application.rb or the development.rb? Here's what I have in my application.rb:
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:user_name => 'XXX#gmail.com',
:password => 'XXX',
:authentication => 'plain',
:enable_starttls_auto => true,
}
Thanks in advance!
Change
def contact(sender, subject, message, sent_at = Time.now)
#sender = sender
#message = message
#sent_at = sent_at.strftime("%B %e, %Y at %H:%M")
mail(:subject => subject)
end
to
def contact(sender, subject, message, recipient, sent_at = Time.now)
#sender = sender
#message = message
#sent_at = sent_at.strftime("%B %e, %Y at %H:%M")
#recipient = recipient
mail(:subject => subject, :to => #recipient)
end
And don't forget to set recipient in your calling function.
Have you put the following lines in development.rb
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
I am very new guy in Rhomobile and I want to login a webservice using Rhoconnect can anyone help me how to implement this.
I've tried with in Settings Controler:
def do_login
if #params['username'] and #params['password']
begin
SyncEngine.login(#params['username'], #params['password'], (url_for :action => :login_callback) )
#response['headers']['Wait-Page'] = 'true'
redirect :action => :index
rescue Rho::RhoError => e
#msg = e.message
render :action => :login
end
else
#msg = Rho::RhoError.err_message(Rho::RhoError::ERR_UNATHORIZED) unless #msg && #msg.length > 0
render :action => :login
end
end
Where SyncEngine.login(#params['username'], #params['password']) call the sourecadapter method login; where I'm calling
def login(username, password)
user_info = {:username => username, :password => password }
response = RestClient.get(#base+#params['username']+#params['password'])
result = RestClient.post(:url => "my-webservice" )
#msg=result["body"]
render :action => :index
end
I've tried in:
class Application < Rhoconnect::Base
class << self
def authenticate(username,password,session)
result = RestClient.post(:url => "mywebservice" )
true # do some interesting authentication here...
end
end
But I got nothing..
plz give some idea me; how to solve this
SyncEngine.login call from Rhodes app will call authenticate(username, password, session)
method in application.rb of your RhoConnect app. Then, you can code the authenticate method to call your implementation of user authentication as follows:
def authenticate(username, password, session)
# for example
resp = RestClient.post(:url => "mywebservice", :login => {:username => username, :password => password})
#parse resp as needed and return the result either true or false
# i.e. status contains value true or false in the response body
result = JSON.parse(resp.body)['status']
end
Hope that helps.