amazon-web-services - AWS S3 公开添加的任何新文件

标签 amazon-web-services amazon-s3 policy

我有一个 AWS S3 存储桶,我让 AWS SES 将原始电子邮件移至该存储桶。我的问题是默认情况下这些电子邮件不是公开的,我需要一个 php 脚本,它可以从这个 S3 存储桶中获取原始文件并将其放入 mysql 中,这样我就无需手动将文件标记为公开在文件夹中。

那么使用我使用 IAM Ke​​y 和 IAM Secret 的下面的代码,我怎样才能让我的下面的脚本加载到具有正确权限的 AWS 存储桶中,以便能够获取原始文件?

 //mysql connection 
  $servername = "***>rds.amazonaws.com";
  $username = "****";
  $password ="***";
  $databasename ="***";

  $rightnowdatetimeis = date('Y-m-d H:i:s');
  $rightnowdateis = date('Y-m-d');

$con = mysqli_connect("$servername","$username","$password","$databasename");

if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}


//load the php mime parse library
require_once __DIR__.'/vendor/autoload.php';

$Parser = new PhpMimeMailParser\Parser();


//Include the AWS SDK using the Composer autoloader.
require 'awssdk/aws-autoloader.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
// AWS Info
$bucketName = 'pipedemail';
$IAM_KEY = '****';
$IAM_SECRET = '***';
// Connect to AWS
try {
    // You may need to change the region. It will say in the URL when the bucket is open
    // and on creation. us-east-2 is Ohio, us-east-1 is North Virgina
    $s3 = S3Client::factory(
        array(
            'credentials' => array(
                'key' => $IAM_KEY,
                'secret' => $IAM_SECRET
            ),
            'version' => 'latest',
            'region'  => 'us-east-1'
        )
    );
} catch (Exception $e) {
    // We use a die, so if this fails. It stops here. Typically this is a REST call so this would
    // return a json object.
    die("Error: " . $e->getMessage());
}

// Use the high-level iterators (returns ALL of your objects).
$objects = $s3->getIterator('ListObjects', array('Bucket' => $bucketName));

foreach ($objects as $object) 
{
    $objectkey = $object['Key'];

    // Get the object
    $result = $s3->getObject(array(
       'Bucket' => $bucketName,
       'Key'    => $objectkey
    ));

    //lets get the raw email file to parse it
    //$Parser->setText($result['Body']);

    //echo "$objectkey";
    $path = "*****";

    //lets get the raw email file to parse it
    $Parser->setText(file_get_contents($path));

    // Once we've indicated where to find the mail, we can parse out the data
    //$to = $Parser->getHeader('to');             // "test" <test@example.com>, "test2" <test2@example.com>
     $addressesTo = $Parser->getAddresses('to'); //Return an array : [[test, test@example.com, false],[test2, test2@example.com, false]]
     $tobrand = $addressesTo[0]['address'];

     $to_brand_domainname = explode("@", "$tobrand", 2)[1]; 
     //lets get the brandid based on the to domain name
     $brandsql = mysqli_query($con, "SELECT brandid FROM brands WHERE branddomainname='$to_brand_domainname' LIMIT 1");
     $brandrow = mysqli_fetch_array($brandsql);
     $brandid = $brandrow['brandid'];

     $from = $Parser->getHeader('from');             // John Smith
     //lets break the full name into a lastname and firstname veriable
     $namepieces = explode(" ", $from);
     $first_name = $namepieces[0];
     $last_name = $namepieces[1];

     $addressesFrom = $Parser->getAddresses('from'); //Return an array : test, test@example.com, false
     $fromname = $addressesFrom[0]['display']; //not sure what this returns yet

     $fromemail = $addressesFrom[0]['address'];
     $subject = $Parser->getHeader('subject');


    //html of email body
    $html_emailbody = $Parser->getMessageBody('html');
   // $htmlEmbedded = $Parser->getMessageBody('htmlEmbedded'); //HTML Body included data


   //First lets see if this email address exists within the database 
    $emailsql = mysqli_query($con, "SELECT cid FROM customer_profiles WHERE email_address='$fromemail' LIMIT 1");
    $erow = mysqli_fetch_assoc($emailsql);
    $cid = $erow['cid'];

   //if customer does not exists
     if($cid < 1)
     {
          $customsql = mysqli_query($con, "INSERT into customer_profiles(first_name, last_name, email_address, last_contact_date) 
                       VALUES('$first_name','$last_name','$fromemail','$rightnowdateis')");
          $cid = mysqli_insert_id($con);
     }

   //create the support issue
     $sql = mysqli_query($con, "INSERT into product_issues(cid, date_created, brandid) VALUES('$cid','$rightnowdatetimeis','$brandid')");
     $issueid = mysqli_insert_id($con);


     mysqli_query($con, "INSERT into customer_notes(cid, date_written, note_body, issueid, note_type, brandid, note_subject, note_status) 
                           VALUES('$cid','$rightnowdatetimeis','$html_emailbody','$issueid','email','$brandid','$subject','unread')");
     $noteid = mysqli_insert_id($con);

    //Pass in a writeable path to save attachments
     $attach_dir = 'email_attachments/';     // Be sure to include the trailing slash
    //$include_inline = false;             // Optional argument to include inline attachments (default: true)
    //$Parser->saveAttachments($attach_dir [,$include_inline]);
    // $Parser->saveAttachments($attach_dir);

    // Get an array of Attachment items from $Parser
    // $attachments = $Parser->getAttachments([$include_inline]);

    //  Loop through all the Attachments
     //   if(count($attachments) > 0) 
     //    {
      //       foreach ($attachments as $attachment) 
      //       {
       //        $fileattachmentname = $attachment->getFilename();
        //        $attachment_filetype = $attachment->getContentType();

            //save file attachement name to database
         //       mysqli_query($con, "INSERT into email_attachments(attachment_name, attachment_filetype, cid, noteid, issueid) 
         //                            VALUES('$fileattachmentname','$attachment_filetype','$cid','$noteid','$issueid')");

            //echo 'Filename : '.$attachment->getFilename().'<br />'; // logo.jpg
            //echo 'Filesize : '.filesize($attach_dir.$attachment->getFilename()).'<br />'; // 1000
            //echo 'Filetype : '.$attachment->getContentType().'<br />'; // image/jpeg
            //echo 'MIME part string : '.$attachment->getMimePartStr().'<br />'; // (the whole MIME part of the attachment)
         //   }
      //  }

    //now lets delete the object since we already took the email and saved it into mysql
    $s3->deleteObject(array('Bucket' => $bucketName, 'Key' => $objectkey)); 
}

最佳答案

如果您希望对您的存储桶进行公共(public)读取访问,那么此策略将执行此操作

{
  "Version":"2012-10-17",
  "Statement":[
    {
      "Sid":"AddPerm",
      "Effect":"Allow",
      "Principal": "*",
      "Action":["s3:GetObject"],
      "Resource":["arn:aws:s3:::examplebucket/*"]
    }
  ]
}

但是您想要对电子邮件执行的操作是借助 ACL 来完成对存储桶对象的公共(public)读取访问,即 Access Control Lists ,并且您不需要授予对存储桶的公共(public)读取权限,因为您的案例需要对对象(即仅电子邮件)的公共(public)读取权限。

在将对象存储到 s3 时,您可以在代码中将该对象的 ACL 设置为 public-read 以完成您的工作

使用 ACL 上传具有公共(public)读取权限的图像的 python 示例

import boto3    

s3client=boto3.client('s3')
s3client.upload_file('filename', 'bucket-name', ktr,ExtraArgs={'ACL': 'public-read'})

您可以在此链接上了解有关 ACL 的更多信息

https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html

关于amazon-web-services - AWS S3 公开添加的任何新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50799764/

相关文章:

java - 如何在Policy中授予用户权限?

security - 上传的白名单或黑名单文件扩展名?

amazon-web-services - react-native-google-signin 与 AWS Cognito

scala - SBT 找不到 hadoop-aws 3.1.1

python - 将 python BOTO 与 AWS SQS 一起使用,找回无意义的字符

java - 检查 S3 复制操作是否成功?

python - 将文件从一个 S3 存储桶移动到另一个最近两天更新的文件

amazon-web-services - Cloudformation 更新堆栈名称或环境的堆栈策略条件

amazon-web-services - 在 cloudformation 中使用 aws_access_key_id 和 aws_access_secret_key 更新路由 53 托管区域

amazon-web-services - 在 AWS Lambda 中运行云形成代码?这可能吗?