ActionMailer是Rails中用于发送邮件的库。它可以使用SMTP协议发送外发邮件。下面是一个示例代码,展示了如何使用ActionMailer发送外发SMTP请求:
首先,确保你已经在Gemfile中添加了ActionMailer库的依赖关系:
gem 'actionmailer'
然后,在Rails应用程序中创建一个邮件发送器(例如,名为user_mailer.rb
的文件):
class UserMailer < ActionMailer::Base
default from: 'your_email@example.com' # 发件人邮箱
def welcome_email(user)
@user = user
mail(to: @user.email, subject: 'Welcome to My App') # 收件人邮箱和邮件主题
end
end
接下来,你需要配置邮件发送的SMTP服务器。在Rails应用程序的配置文件(例如,config/environments/development.rb
)中添加以下代码:
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.example.com', # SMTP服务器地址
port: 587, # SMTP服务器端口
domain: 'example.com', # 发件人域名
user_name: 'your_username', # SMTP服务器的用户名
password: 'your_password', # SMTP服务器的密码
authentication: 'plain', # 验证类型(例如,plain,login,cram_md5等)
enable_starttls_auto: true # 启用STARTTLS加密
}
最后,在控制器或其他适当的地方调用邮件发送器的方法:
UserMailer.welcome_email(@user).deliver_now
这将发送一封包含欢迎信息的邮件给@user
对象的邮箱。
以上就是使用ActionMailer发送外发SMTP请求的示例代码。你可以根据自己的需求进行相应的修改和配置。