Rails 5发送带附件的HTML电子邮件

时间:2017-09-04 06:15:03

标签: ruby-on-rails email html-email email-attachments

因此,在我的应用中,用户可以创建他们发送给"联系人"他们在应用程序中。

该应用使用CKEditor文本框让用户输入电子邮件正文。 他们还可以将文件附加到电子邮件中。

使用此代码发送电子邮件,文件已正确附加,但所有HTML标记都显示在电子邮件正文中。

控制器

@file = EmailFile.create! file: params[:attachment]
@attachment_path = @file.file.url
@file_name = @file.file_file_name

email_params = {
  to: email_recipients,
  from: current_user.email,
  subject: params[:email_subject],
  body: params[:email_body]
}

CustomMailer.send_individual_email(email_params, @attachment_path, @file_name).deliver_now!

邮件程序

  def send_individual_email(email_params, attachment_path, file_name)
    if file_name.present?
      open_file = open(attachment_path)
      attachments[file_name] = File.read(open_file)
    end

    mail(to: email_params[:to],
         from: email_params[:from],
         subject: email_params[:subject],
         body: email_params[:body])
  end

send_individual_email.html.erb

<!DOCTYPE html>
<html xmlns=3D"http://www.w3.org/1999/xhtml" dir=3D"auto">
<head>
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
</head>
<body>
  <%= body.html_safe %>
</body>
</html>

还有一个send_individuial_email.text.erb文件。

如果我更改Mailer以添加content_type,附件将成为电子邮件中的乱码文本,但HTML标签会正确格式化文本

邮件程序

mail(to: email_params[:to],
     from: email_params[:from],
     subject: email_params[:subject],
     content_type: 'text/html',
     body: email_params[:body])

Rails 5.0.1应用程序托管在Heroku上,并使用Sendgrid发送电子邮件。

我尝试更改content_type以及删除视图中的.html_safe。

我可以通过身体的附件和纯文本,或者没有附件和标记文本显示在正文中但不能同时使用这两种情况,使电子邮件正常工作。

我知道肯定会有一些我做错的事。

如何使用附件发送带有标记文本的电子邮件?

谢谢!

0 个答案:

没有答案