gpt4 book ai didi

php - Gmail API PHP 客户端库 - 如何使用 PHP 客户端库创建带有附件的电子邮件草稿?

转载 作者:搜寻专家 更新时间:2023-10-31 21:07:57 27 4
gpt4 key购买 nike

我正在使用 Google 的 PHP 客户端库向 Gmail 的 API 发送调用。使用这些资源,我可以创建电子邮件草稿。但我终其一生都无法弄清楚如何使用客户端库来创建带附件的电子邮件草稿。两周以来,我一直在阅读我能在网上找到的所有内容,但我仍然没有找到答案。

这似乎很简单。有人知道答案吗?

谢谢!

编辑:感谢 johncorser 在正确方向上的插入。使用 zetacomponents,我能够正确地构建消息(在使用 PHPMailer 和 Mail_mime 失败两周后)。这是我的最终代码:

<?php

session_start();

require 'Google/autoload.php';
require 'Google/Client.php';
require 'Google/Service/Gmail.php';
require 'ezc/Base/base.php';

spl_autoload_register( array( 'ezcBase', 'autoload' ) );


//Get credential
$config = parse_ini_file('helpers/config.ini');

// Setup Google API Client
$client = new Google_Client();
$client->setClientId($config['client_id']);
$client->setClientSecret($config['client_secret']);
$client->setRedirectUri($config['redirect_url']);
$client->addScope('https://www.googleapis.com/auth/gmail.modify');

// Create GMail Service
$service = new Google_Service_Gmail($client);

// Check if user is logged out
if(isset($_REQUEST['logout'])){
unset($_SESSION['access_token']);
}

// Check if we have an authorization code; if so, use it
if(isset($_GET['code'])){
$code = $_GET['code'];
$client->authenticate($code);
$_SESSION['access_token'] = $client->getAccessToken();
$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($url,FILTER_VALIDATE_URL));
}

// Check if we have an access token in the session; if so, setup input form; if not, create auth URL
if(isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
echo "<form action='' method='post' enctype='multipart/form-data'>
<p>Your First Name: <input type='text' name='first' required></p>
<p>Your Last Name: <input type='text' name='last' required></p>
<p>Body (without any greeting):</p> <textarea rows='20' cols='100' name='body' required></textarea>
<p>Select headshot (JPG, JPEG, PNG, or GIF) to upload: <input type='file' name='headshotToUpload' id='headshotToUpload' required></p>
<p>Select resume PDF to upload: <input type='file' name='resumeToUpload' id='resumeToUpload' required></p>
<p><input type='submit' name='submit' value='Create Drafts'></p></form>";

} else {
$loginUrl = $client->createAuthUrl();
}

//If auth URL is set, create llink for user to login; otherwise, show logout link
if (isset($loginUrl)) {
echo "<a class='login' href='" . $loginUrl . "'>First Click Here to Connect Through Google!</a>";
} else {
echo "<a class='logout' href='?logout'>Logout</a>";
}

//Once submit button is pressed, begin file upload process
if(isset($_POST['submit'])) {
$target_dir = "uploads/";
$target_hsfile = $target_dir . basename($_FILES["headshotToUpload"]["name"]);
$target_cvfile = $target_dir . basename($_FILES["resumeToUpload"]["name"]);
$uploadOk = 1;

//Check if filenames already exist
if (file_exists($target_hsfile)) {
echo "Please rename your headshot before uploading.";
$uploadOk = 0;
}

if (file_exists($target_cvfile)) {
echo "Please rename your resume before uploading.";
$uploadOk = 0;
}

//Check that file types are permitted
$hsFileType = pathinfo($target_hsfile,PATHINFO_EXTENSION);
if($hsFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for headshots.";
$uploadOk = 0;
}

$cvFileType = pathinfo($target_cvfile,PATHINFO_EXTENSION);
if($cvFileType != "pdf") {
echo "Sorry, resumes must be in PDF format only.";
$uploadOk = 0;
}

//Report on success or failure of upload
if ($uploadOk == 0) {
echo "Sorry, your files were not uploaded. Please correct the noted error(s) and try again";
} else {
// If everything is ok, try to upload file
if ((move_uploaded_file($_FILES["headshotToUpload"]["tmp_name"], $target_hsfile)) && ((move_uploaded_file($_FILES["resumeToUpload"]["tmp_name"], $target_cvfile)))) {
echo "The files ". basename( $_FILES["headshotToUpload"]["name"]). " and ". basename( $_FILES["resumeToUpload"]["name"]). " have been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}

//Load data
$agent_data = parse_ini_file('helpers/agents.ini', true);

//Iterate through agencies


foreach ($agent_data as $agency) {

$mail = new ezcMail();

$mail->addTo( new ezcMailAddress($agency['agent_email'], $agency['agent_first']." ".$agency['agent_last'] ));
$mail->subject = "Submission of " . $_POST['first'] . " " . $_POST['last'] . " to " . $agency['agency_name'];
$textpart = new ezcMailText("Dear " . $agency['agent_salut'] . " " . $agency['agent_last'] . "," . "\r\n" . "\r\n" . $_POST['body'] . "\r\n" . "\r\n" . "Sincerely," . "\r\n" . "\r\n" . $_POST['first'] . " " . $_POST['last']);
$fileAttachment1 = new ezcMailFile($target_hsfile);
$fileAttachment2 = new ezcMailFile($target_cvfile);
$mail->body = new ezcMailMultipartMixed( $textpart, $fileAttachment1, $fileAttachment2 );
$message = $mail->generate();

$msgbody = new Google_Service_Gmail_Message();

$msgbody->setRaw(rtrim(strtr(base64_encode($message), '+/', '-_'), '='));

$draft = new Google_Service_Gmail_Draft();

$draft->setMessage($msgbody);

$service->users_drafts->create('me', $draft);

unset($mail);
unset($msgbody);
unset($draft);

}

}

?>

最佳答案

如果您有原始电子邮件消息,这很容易。我会尝试这样的事情:

public function save_draft(Google_Service_Gmail $gmail, $raw_message, $gmail_thread_id = null)
{
$postBody = new Google_Service_Gmail_Message();
$postBody->setRaw(rtrim(strtr(base64_encode($raw_message), '+/', '-_'), '=');
if ($gmail_thread_id)
$postBody->setThreadId($gmail_thread_id);

$draft = new Google_Service_Gmail_Draft();
$draft->setMessage($postBody);
return $gmail->users_drafts->create('me', $draft);
}

此函数应创建一个草稿,将该草稿添加到您传入的任何 gmail 线程,然后返回结果。这种奇怪的 base64_encode 业务的原因是因为 gmail api 需要一个相当具体的编码。您应该能够只在原始正文中包含附件。

关于php - Gmail API PHP 客户端库 - 如何使用 PHP 客户端库创建带有附件的电子邮件草稿?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29068417/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com