markdown 发送电子邮件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown 发送电子邮件相关的知识,希望对你有一定的参考价值。
### Sending an Email
* Set up an app (where a User model has an email)
* Next, run `rails g mailer name_of_mailer`
* This will create some files in `app/mailers/name_of_mailer.rb` and some in the test unit
```ruby
# app/mailers/name_of_mailer.rb
class NameOfMailer < ActionMailer:: Base
default from: "from@example.com"
end
```
* Add custom functions to customize your email
* Change the default email to the email address you want to use as the sender's email address
```ruby
# app/mailers/name_of_mailer.rb
class NameOfMailer < ActionMailer:: Base
default from: "from@example.com"
def sample_email(user)
@user = user
mail(to: @user.email, subject: "Sample Email")
end
end
```
---
### Mail Contents
* To write the actual contents of the mail, navigate to `app/views/name_of_mailer` and create a
file with a `.html.erb` extension
```html
<!DOCTYPE html>
<html>
<head>
<meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
</head>
<body>
<h1>Hi <%= @user.name %></h1>
<p>
Sample mail sent using smtp.
</p>
</body>
</html>
```
* You can also create a text version, incase you prefer your user's to not have an HTML email
* In the same directory, create a file with a `.text.erb` extension
```ruby
Hi <%= @user.name %>
Sample mail sent using smtp.
```
---
### Previewing an Email
* You can preview an email before sending it out by navigating in the browser to
`/rails/name_of_mailer/function_name`
* in the case below: `http://localhost:3000/rails/mailers/example_mailer/sample_mail_preview`
* But first you will need to set up a user, so in `test/mailers/previews/name_of_mailer_preview.rb`
use the following code:
```ruby
class ExampleMailerPreview < ActionMailer::Preview
def sample_mail_preview
ExampleMailer.sample_email(User.first)
end
end
```
---
### How does Rails send emails?
* By default, Rails uses SMTP (Simple Mail Transfer Protocol)
* You will need to provide SMTP configurations in environment settings `config/environments/`
* Store the email and password in the `secrets.yml` file
```ruby
config.action_mailer.delivery_method = :smtp
# SMTP settings for gmail
config.action_mailer.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:user_name => ENV['gmail_username'],
:password => ENV['gmail_password'],
:authentication => "plain",
:enable_starttls_auto => true
}
```
* Typically, you want to send emails from the production environment (you can still send to dev
environment, makes more sense to not clog up emails in dev env)
---
## Sending an email linked to Controller Action
* In the action that you want the email to be sent: `NameOfMailer.sample_email(@user).deliver`
以上是关于markdown 发送电子邮件的主要内容,如果未能解决你的问题,请参考以下文章
markdown 从Linux命令行发送电子邮件(postfix或netcat)