How do I send email using gmail api php
$msg['raw'] = "This is sample test message";
$msg['To'] = "test.api#gmail.com";
$msg['subject'] = "Sample test subject";
currently i am using $message = $service->users_messages->send('me', $msg);
Where to difine to,subject ?
Based on http://www.pipiscrew.com/2015/04/php-send-mail-through-gmail-api/ here is the answer:
$user = 'me';
$strSubject = 'Test mail using GMail API' . date('M d, Y h:i:s A');
$strRawMessage = "From: myAddress<myemail#gmail.com>\r\n";
$strRawMessage .= "To: toAddress <recptAddress#gmail.com>\r\n";
$strRawMessage .= 'Subject: =?utf-8?B?' . base64_encode($strSubject) . "?=\r\n";
$strRawMessage .= "MIME-Version: 1.0\r\n";
$strRawMessage .= "Content-Type: text/html; charset=utf-8\r\n";
$strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
$strRawMessage .= "this <b>is a test message!\r\n";
// The message needs to be encoded in Base64URL
$mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
$msg = new Google_Service_Gmail_Message();
$msg->setRaw($mime);
//The special value **me** can be used to indicate the authenticated user.
$service->users_messages->send("me", $msg);
Swiftmailer has all the tools for building base64 message.
Here is a full sample for sending a email:
// Visit https://developers.google.com/gmail/api/quickstart/php
// for an example of how to build the getClient() function.
$client = getClient();
$service = new \Google_Service_Gmail($client);
$mailer = $service->users_messages;
$message = (new \Swift_Message('Here is my subject'))
->setFrom('myemailaddress#myserver.com')
->setTo(['receiver#someserver.com' => 'Test Name'])
->setContentType('text/html')
->setCharset('utf-8')
->setBody('<h4>Here is my body</h4>');
$msg_base64 = (new \Swift_Mime_ContentEncoder_Base64ContentEncoder())
->encodeString($message->toString());
$message = new \Google_Service_Gmail_Message();
$message->setRaw($msg_base64);
$message = $mailer->send('me', $message);
print_r($message);
Edit in November 2021
Swiftmailer has reached its end of life. See swiftmailer's author blog post.
From now on you should use the Symfony Mailer component.
I am using the same code and it does work fine except that it always sends a plain text email.
Isn't specifying Content-Type: text/html; enough?
Related
I have an mail.php file in root on my hosting space.
Do I call mail.php with axios from my localhost from within the development server (npm start) it works fine.
The form who triggers the POST sends the data to my Email address.
After the build process and the upload on my web space, I still receive an email but there the input is missing.
Axios POST:
const formData = new FormData();
// formData.append('name', datas.name);
// formData.append('email', datas.email);
// formData.append('message', datas.message);
// formData.append('nice', nice)
formData.append('name', 'Klara');
formData.append('email', 'klara#gmail.com');
formData.append('message', 'Hallo');
//POST data to the php file
try{
axios.post('https://salevsky.net/mail.php', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
} catch(error) {
PHP file:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: multipart/form-data');
$to = "blablub#webyy.net";
$subject = "Contact Us";
// // Email Template
$message .= "<b>Message : </b>".$_POST['name']."<br>";
$message .= "<b>Email Address : </b>".$_POST['email']."<br>";
$message .= "<b>Message : </b>".$_POST['message']."<br>";
$header = "From:".$_POST['email']." \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retval = mail ($to,$subject,$message,$header);
// // message Notification
if( $retval == true ) {
echo json_encode(array(
'success'=> true,
'message' => 'Message sent successfully'
));
}else {
echo json_encode(array(
'error'=> true,
'message' => 'Error sending message'
));
}
?>
I tried various DataTypes and ContentForms.
At least headers: { "Content-Type": "multipart/x-www-form-urlencoded" },
I wonder why content type in request header is not changing. I see this in the Browser under Network. It's application/json all time. But I don't know if it's an important fact.
I struggle with Authentication request to gate.io apiv4
Reference:
https://www.gate.io/docs/apiv4/en/#api-signature-string-generation
I'm getting this response:
{"label":"INVALID_SIGNATURE","message":"Signature mismatch"}"
My code:
function signature($method, $url, $body, $timestamp) {
$body = is_array($body) ? json_encode($body) : $body;
$fullPath = parse_url($this->host, PHP_URL_PATH) . $url;
$fmt = "%s\n%s\n%s\n%s\n%s";
$hashedPayload = hash("sha512", $body);
$signatureString = sprintf(
$fmt,
$method,
$fullPath,
"",
$hashedPayload,
$timestamp
);
$signature = hash_hmac("sha512", $signatureString, $this->SECRET_KEY);
return $signature;
}
not sure where the error is, does anyone have similar issues?
Thank you
I am trying to add failed test attachments in the Test tab in Azure DevOps using VS test task.
I am calling the Create Test Result Attachment rest api,
$AzureDevOpsPAT = {PAT}
$AzureDevOpsAuthenicationHeader = #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($AzureDevOpsPAT)")) }
$result = Invoke-RestMethod -Uri https://dev.azure.com/{org}/{proj}/_apis/test/runs/$(runId)/results?api-version=6.0 -Headers $AzureDevOpsAuthenicationHeader -Method Get
#List all test result get the test result ID via result
foreach($Run in $result.value){
#Get the test result ID via result
If($Run.outcome -eq "Failed"){
$TestResultID = $Run.id
$Name=$Run.testCase.name
Write-Host $TestResultID $Name
#Add attachment via test run ID and test result ID
$TestResultAttachmentURL = "https://dev.azure.com/{org}/{proj}/_apis/test/Runs/$(runId)/results/$($TestResultID)/attachments?api-version=6.0-preview.1"
$body =#"
{
"stream": "abc",
"fileName": "$(System.DefaultWorkingDirectory)/$Name.png",
"comment": "Test attachment upload",
"attachmentType": "GeneralAttachment"
}
"#
$TestResultAttachmentResult = Invoke-RestMethod -Uri $TestResultAttachmentURL -ContentType "application/json" -Body $body -Headers $AzureDevOpsAuthenicationHeader -Method POST
}
}
I cant see the respective screenshot, the black flower is showing if I click on .png file in the attachment tab,
Though I am capturing a screenshot in my code too,
protected void StopWebDriver()
{
if (WebDriver != null)
{
string path = Directory.GetCurrentDirectory() + "\\" + BaseConfig.TestCaseName + ".png";
((ITakesScreenshot)WebDriver).GetScreenshot().SaveAsFile(path, ScreenshotImageFormat.Png);
WebDriver.Close();
WebDriver.Quit();
}
}
Can anyone please tell me how can I see screenshots?
Based on my test , the screenshot could show in the Pipeline -> Test -> Attachment tab.
You could use the PowerShell Script to generate the Base64 file Stream instead of hardcode the file stream.
Here is an example:
$file= [IO.File]::ReadAllBytes("filepath\$Name.png")
$Base64file= [Convert]::ToBase64String($file)
echo $Base64file
$token = "PAT"
$url="https://dev.azure.com/{org}/{proj}/_apis/test/Runs/$(runId)/results/$($TestResultID)/attachments?api-version=6.0-preview.1"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$JSON = "
{
`"stream`": `"$Base64file`",
`"fileName`": `"$Name.png`",
`"comment`": `"Test attachment upload`",
`"attachmentType`": `"GeneralAttachment`"
}"
$response = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Basic $token"} -Method Post -Body $JSON -ContentType application/json
On the other hand, you could directly try to use the Publish screenshots for test failure task from the extension Publish test result screenshot.
In addition, in order to confirm whether the image you uploaded is valid, you can also download and check whether it is the correct content.
Update:
To get the Test case name in a string, you could refer to this sample:
$String= "ooo.iii.kkk.lll"
$a,$b,$c,$d = $String.Split(".",4)
echo $c
Powershell script task1 to get the run id:
$AzureDevOpsPAT = {PAT}
$AzureDevOpsAuthenicationHeader = #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($AzureDevOpsPAT)")) }
$UriOrga = "https://dev.azure.com/{org}/{proj}/"
$uriAccount = $UriOrga + "_apis/test/runs?api-version=6.0"
$response = Invoke-RestMethod -Uri $uriAccount -Headers $AzureDevOpsAuthenicationHeader -Method Get
$testRunsIdSorted = $response.value | sort-object id -Descending
$result = Invoke-RestMethod -Uri https://dev.azure.com/{org}/{proj}/_apis/test/runs/$($testRunsIdSorted[0].id)?api-version=6.0 -Headers $AzureDevOpsAuthenicationHeader -Method Get
Write-Host "results = $($result | ConvertTo-Json -Depth 100)"
Write-Host "##vso[task.setvariable variable=runId]$($result.id | ConvertTo-Json -Depth 100)"
Powershell task2 to attach the screenshot attachment:
$AzureDevOpsPAT = {PAT}
$AzureDevOpsAuthenicationHeader = #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($AzureDevOpsPAT)")) }
$result = Invoke-RestMethod -Uri https://dev.azure.com/{org}/{proj}/_apis/test/runs/$(runId)/results?api-version=6.0 -Headers $AzureDevOpsAuthenicationHeader -Method Get
#List all test result get the test result ID via result
foreach($Run in $result.value){
#Get the test result ID via result
If($Run.outcome -eq "Failed"){
$TestResultID = $Run.id
$TestTitle=$Run.testCase.name
$CharArray =$TestTitle.Split(".")
$TestCase=$CharArray[6]
$CharArraytwo=$TestCase.Split("(")
$TestName =$CharArraytwo[0]
$file= [IO.File]::ReadAllBytes("$(System.DefaultWorkingDirectory)\{Source alias}\tests\{testproject}\bin\Release\$TestName.png")
$Base64file= [Convert]::ToBase64String($file)
#Add attachment via test run ID and test result ID
$TestResultAttachmentURL = "https://dev.azure.com/{org}/{proj}/_apis/test/Runs/$(runId)/results/$($TestResultID)/attachments?api-version=6.0-preview.1"
$body =#"
{
"stream": "$Base64file",
"fileName": "$TestName.png",
"comment": "Test attachment upload",
"attachmentType": "GeneralAttachment"
}
"#
$TestResultAttachmentResult = Invoke-RestMethod -Uri $TestResultAttachmentURL -ContentType "application/json" -Body $body -Headers $AzureDevOpsAuthenicationHeader -Method POST
}
}
The C# code was correct. In VS test task, PowerShell tasks remember to enable "Conitnue on error". Otherwise, if the task failed, others will not execute.
My question is when i create new user in SUITECRM, i want to insert data in another application and other CodeIgniter database.
Please help me, about how to solve above problem.
I have create custom insert insert api like:
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// get database connection
include_once '../config/database.php';
// instantiate product object
include_once '../objects/product.php';
$database = new Database();
$db = $database->getConnection();
$product = new Product($db);
//get posted data
$data = (object) $_POST;
//$data = json_decode(file_get_contents("php://input"));
// set product property values
$product->name = $data->name;
$product->description = $data->description;
$product->price = $data->price;
$product->category_id = $data->category_id;
$product->created = date('Y-m-d H:i:s');
// create the product
if($product->create()){
echo '{';
echo '"message": "Product was created."';
echo '}';
}
// if unable to create the product, tell the user
else{
echo '{';
echo '"message": "Unable to create product."';
echo '}';
}
?>
I am using Guzzle 3.8.1 with CakePHP 2.5.6 and I am making a call to the Box API. I would like to be able to refresh my access token when it expires. The issue I am encountering is that I may be using any one of N possible access tokens and I want to be able to use the $account_id that is in scope for the function I am defining this in. I don't see how I can pass it into the Listener defined function, since I am not calling that myself. I do see that the expired access_token exists in the $event variable, but I would have to locate it and then parse it from the header that I am passing to Box. I think I could add a custom header containing the account_id, but that seems like a bad way to approach the problem. Can I somehow specify a variable in the request that wouldn't be added as part of the call to Box? Any suggestions are much appreciated, thanks!
`
public function get_folder_list ($account_id = null, $parent_folder_id = null) {
// Get account
$this->Account = ClassRegistry::init('Account');
$account = $this->Account->findById($account_id);
$this->Account->log($account);
// If account doesn't exist, throw error
if(empty($account)) {
throw new NotFoundException(__('Account id not found: ' . $account_id));
}
// Call Box for folder list
$box_url = "https://api.box.com/2.0/folders/";
if (empty($parent_folder_id)) {
$box_url .= "0";
} else {
$box_url .= $parent_folder_id;
}
$this->Account->log($box_url);
$bearer = 'Bearer ' . $account['Account']['access_token'];
$client = new Guzzle\Http\Client();
$client->getEventDispatcher()->addListener('request.error', function(Event $event) {
if ($event['response']->getStatusCode() == 401) {
$Account = new Account;
$Account->log($event);
$Box = new BoxLib;
$account = $Box->refresh_token($account_id);
$bearer = 'Bearer ' . $account['Account']['access_token'];
$request = $client->get($box_url, array('Authorization' => $bearer));
$event['response'] = $newResponse;
$event->stopPropagation();
}
});
$request = $client->get($box_url, array('Authorization' => $bearer));
try {
$response = $request->send();
} catch (Guzzle\Http\Exception\BadResponseException $e) {
// HTTP codes 4xx and 5xx throw BadResponseException
$this->Account->log('Service exception!');
$this->Account->log('Uh oh! ' . $e->getMessage());
$this->Account->log('HTTP request URL: ' . $e->getRequest()->getUrl() . "\n");
$this->Account->log('HTTP request: ' . $e->getRequest() . "\n");
$this->Account->log('HTTP response status: ' . $e->getResponse()->getStatusCode() . "\n");
$this->Account->log('HTTP response: ' . $e->getResponse() . "\n");
}
$this->Account->log($response->json());
$json = $response->json();
$folder_list = array();
foreach ($json['item_collection']['entries'] as $folder) {
$folder_list[$folder['id']] = $folder['name'];
}
//$this->Account->log($folder_list);
return $folder_list;
}
`