繁体   English   中英

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

[英]Gmail API PHP Client Library - How do you create a draft email with an attachment using the PHP client library?

我正在使用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需要一个相当具体的编码。 您应该能够将附件包含在原始主体中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM