在Codeigniter中使用Mailgun发送带附件的邮件可以通过curl来实现。以下是详细步骤:
sudo apt-get install php-curl
Mailgun_lib.php
。在这个函数中,你需要使用curl来发送HTTP POST请求到Mailgun API,并传递必要的参数和附件。<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Mailgun_lib {
private $api_key = 'YOUR_MAILGUN_API_KEY';
private $api_base_url = 'https://api.mailgun.net/v3/YOUR_DOMAIN_NAME';
public function send_email_with_attachment($to, $subject, $message, $attachment_path) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $this->api_base_url . '/messages',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => array(
'from' => 'YOUR_SENDER_EMAIL',
'to' => $to,
'subject' => $subject,
'text' => $message,
'attachment' => curl_file_create($attachment_path)
),
CURLOPT_HTTPHEADER => array(
'Authorization: Basic ' . base64_encode('api:' . $this->api_key)
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo 'cURL Error #:' . $err;
} else {
echo $response;
}
}
}
send_email_with_attachment
函数来发送带附件的邮件。<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Email_controller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('mailgun_lib');
}
public function send_email() {
$to = 'recipient@example.com';
$subject = 'Test Email with Attachment';
$message = 'This is a test email with attachment.';
$attachment_path = '/path/to/attachment/file.pdf';
$this->mailgun_lib->send_email_with_attachment($to, $subject, $message, $attachment_path);
}
}
以上代码中的YOUR_MAILGUN_API_KEY
需要替换为你的Mailgun API密钥,YOUR_DOMAIN_NAME
需要替换为你的Mailgun域名,YOUR_SENDER_EMAIL
需要替换为你的发件人邮箱地址。
这样,当你调用send_email
函数时,Codeigniter将使用curl发送HTTP POST请求到Mailgun API,并将附件作为参数传递。你可以根据需要自定义其他邮件参数,比如CC、BCC、HTML内容等。
请注意,为了使代码更加健壮和安全,你可能需要添加错误处理和验证逻辑,以确保邮件发送成功并处理潜在的异常情况。
领取专属 10元无门槛券
手把手带您无忧上云