首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Gmail客户端库-如何使用PHP客户端库创建带有附件的电子邮件草稿?

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

Stack Overflow用户
提问于 2015-03-16 01:41:45
回答 1查看 2.2K关注 0票数 4

我正在使用Google的PHP客户端库向Gmail的API发送调用。利用这些资源,我可以创建电子邮件草稿。但在我的一生中,我想不出如何使用客户端库创建带有附件的电子邮件草稿。我已经在网上阅读了两周了,但我仍然没有答案。

这似乎是直接的。有人知道答案吗?

谢谢!

编辑:感谢johncorser向正确方向的推进。使用zetacomponents,我能够正确地构建消息(在PHPMailer和Mail_mime失败了两个星期之后)。这是我的最后代码:

代码语言:javascript
运行
复制
<?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);

    }           

}       

?>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-16 15:46:45

这是相当容易,如果你有原始的电子邮件信息。我想试一试:

代码语言:javascript
运行
复制
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需要相当具体的编码。你应该能够把附件包含在原始的身体里。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29068417

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档