在CentOS上使用Laravel发送邮件,你需要遵循以下步骤:
composer create-project --prefer-dist laravel/laravel your_project_name
将your_project_name替换为你的项目名称。
.env文件中配置邮件服务。Laravel支持多种邮件服务提供商,如SMTP、Mailgun、SendGrid等。这里以SMTP为例,你需要填写以下信息:MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=your_email@example.com
MAIL_FROM_NAME="${APP_NAME}"
将your_username、your_password和your_email@example.com替换为你的SMTP服务提供商提供的凭据。
resources/views目录下创建一个新的MHTML文件,例如email_template.blade.php。在这个文件中编写你的邮件模板。例如:<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Email Template</title>
</head>
<body>
<h1>Hello, {{ $name }}!</h1>
<p>This is a test email sent from Laravel.</p>
</body>
</html>
Mail门面来发送邮件。首先,你需要在控制器顶部引入Mail门面和你的邮件模板:use Illuminate\Support\Facades\Mail;
use App\Mail\YourEmailTemplate;
然后,在需要发送邮件的地方调用Mail::to()方法,并传入收件人的电子邮件地址和邮件模板数据:
Mail::to('recipient@example.com')->send(new YourEmailTemplate(['name' => 'John Doe']));
将recipient@example.com替换为实际的收件人电子邮件地址,将YourEmailTemplate替换为你创建的邮件模板类名。
app/Mail目录下创建一个新的PHP文件,例如YourEmailTemplate.php。在这个文件中定义你的邮件模板类,继承自Illuminate\Notifications\Messages\MailMessage:namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
class YourEmailTemplate extends Notification
{
use Queueable;
public function __construct($data)
{
$this->name = $data['name'];
}
public function build()
{
return new MailMessage
->subject('Email Subject')
->markdown('email_template');
}
}
将YourEmailTemplate替换为你创建的邮件模板类名,将email_template替换为你创建的MHTML文件名(不包括扩展名)。
现在,当你调用Mail::to()->send()方法时,Laravel将使用你定义的邮件模板类和模板文件来发送邮件。