Retrieving Emails Using Laravel and IMAP,failed to pass variable to view - email

I have written a code to display emails form gmail:
public function getMail()
{
/* connect to gmail */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'xyz#gmail.com';
$password = 'xyz';
$inbox = imap_open($hostname, $username, $password) or die('Cannot connect: ' . imap_last_error());
$emails = imap_search($inbox, 'ALL');
if ($emails) {
$output = '';
rsort($emails);
foreach ($emails as $email_number) {
$header = imap_headerinfo($inbox, $email_number);
$from = $header->from[0]->mailbox . "#" . $header->from[0]->host;
$toaddress = $header->toaddress;
echo '<strong>To:</strong> ' . $toaddress . '<br>';
echo '<strong>From:</strong> ' . $from . '<br>';
$message = quoted_printable_decode(imap_fetchbody($inbox,$email_number,1.1));
if ($message == '') {
$message = (imap_fetchbody($inbox, $email_number, 1));
echo '<strong>Body:</strong> ' . $message . '<br>';
echo '<br>';
}
}
}
imap_expunge($inbox);
imap_close($inbox);
}
This works fine, but when i pass variables '$toaddress', '$from' to view it shows only first email id. And i have to add a view button,upon click of that there should come body of that respective email and goes to different method, i passed para $message to that method,
$this->showMail($message);
and method is:
public function showMail($message){
return view('emails.showmail',compact('message'));
}
but on click of button there is missing argument error. If anyone knows help me through this!

I did some changes and it worked!
public function getMail()
{
/* connect to gmail */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'xyz#gmail.com';
$password = 'xyz';
$inbox = imap_open($hostname, $username, $password) or die('Cannot connect: ' . imap_last_error());
$emails = imap_search($inbox, 'ALL');
if ($emails) {
$output = '';
$mails = array();
rsort($emails);
foreach ($emails as $email_number) {
$header = imap_headerinfo($inbox, $email_number);
$message = quoted_printable_decode (imap_fetchbody($inbox, $email_number, 1));
$from = $header->from[0]->mailbox . "#" . $header->from[0]->host;
$toaddress = $header->toaddress;
if(imap_search($inbox, 'UNSEEN')){
/*Store from and message body to database*/
DB::table('email')->insert(['from'=>$from, 'body'=>$message]);
return view('emails.display');
}
else{
$data = Email::all();
return view('emails.display',compact('data'));
}
}
}
imap_close($inbox);
}
public function showMail($id){
// get the id
$message = Email::findOrFail($id);
$m = $message->body;
// show the view and pass the nerd to it
return view('emails.showmail',compact('m'));
}
I stored all my emails in my own database, and then displayed in display.blade.php.
display.blade.php:
<div class="page-header">
<h1>Inbox</h1>
</div>
<div class="row">
<div class="col-sm-4">
#foreach ( $data as $from )
{!! $from->from !!} <br>
View
<hr>
#endforeach
</div>
</div>

Related

How do you create an Outlook Appointment / Meeting in PowerShell?

How do you create an Outlook Appointment / Meeting in PowerShell?
The following code will create an Outlook Appointment in PowerShell.
Function Create-Appointment(){
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)][String]$Subject,
[Parameter(Mandatory=$true)][DateTime]$MeetingStart,
[Parameter()][String]$Recipients,
[Parameter()][String]$Categories,
[Parameter()][String]$Location,
[Parameter()][String]$Body=$Subject,
[Parameter()][int]$ReminderMinutesBeforeStart=15,
[Parameter()][int]$DurationInMinutes=30
)
$ol = New-Object -ComObject Outlook.Application
$meeting = $ol.CreateItem('olAppointmentItem')
if($ReminderMinutesBeforeStart -gt 0){
$meeting.ReminderSet = $true
$meeting.ReminderMinutesBeforeStart = $ReminderMinutesBeforeStart
}
if($PSBoundParameters.ContainsKey('Recipients')){
foreach($email in $Recipients -split ";"){
if($email -ne ''){
$meeting.Recipients.Add($email)
}
}
$meeting.MeetingStatus = [Microsoft.Office.Interop.Outlook.OlMeetingStatus]::olMeeting
} else {
$meeting.MeetingStatus = [Microsoft.Office.Interop.Outlook.OlMeetingStatus]::olNonMeeting
}
if($PSBoundParameters.ContainsKey('Location')){
$meeting.Location = $Location
}
if($PSBoundParameters.ContainsKey('Categories')){
$meeting.Categories = $Categories
}
$meeting.Subject = $Subject
$meeting.Body = $Body
$meeting.Start = $MeetingStart
$meeting.Duration = $DurationInMinutes
$meeting.Save()
$meeting.Send()
}

why this powershell http server code doesn't work

I copied and pasted this code https://community.idera.com/database-tools/powershell/powertips/b/tips/posts/creating-powershell-web-server in a powershell console directory which contains an index.html file
when browsing to http://localhost:8080/index.html I get an error Oops, the page is not available!
Is there something wrong with the code I can't see what ?
# enter this URL to reach PowerShell’s web server
$url = 'http://localhost:8080/'
# HTML content for some URLs entered by the user
$htmlcontents = #{
'GET /' = '<html><building>Here is PowerShell</building></html>'
'GET /services' = Get-Service | ConvertTo-Html
}
# start web server
$listener = New-Object System.Net.HttpListener
$listener.Prefixes.Add($url)
$listener.Start()
try
{
while ($listener.IsListening) {
# process received request
$context = $listener.GetContext()
$Request = $context.Request
$Response = $context.Response
$received = '{0} {1}' -f $Request.httpmethod, $Request.url.localpath
# is there HTML content for this URL?
$html = $htmlcontents[$received]
if ($html -eq $null) {
$Response.statuscode = 404
$html = 'Oops, the page is not available!'
}
# return the HTML to the caller
$buffer = [Text.Encoding]::UTF8.GetBytes($html)
$Response.ContentLength64 = $buffer.length
$Response.OutputStream.Write($buffer, 0, $buffer.length)
$Response.Close()
}
}
finally
{
$listener.Stop()
}
It does work if you go to just http://localhost:8080/, you'd have to also have an index.html listing in order to browse to that too.
Just modify the $htmlContents section like so:
# HTML content for some URLs entered by the user
$htmlcontents = #{
'GET /' = '<html><building>Here is PowerShell</building></html>'
'GET /services' = Get-Service | ConvertTo-Html
'GET /index.html' = '<html><building>this is my index page</building></html>'
}
You could also have a statement like this.
$htmlcontents = #{
'GET /' = '<html><building>Here is PowerShell</building></html>'
'GET /services' = Get-Service | ConvertTo-Html
'GET /index.html' = '<html><building>this is my index page</building></html>'
'GET /fromPage.html' = Get-content "C:\temp\fence.txt"
}

Add multiline body to powershell email

I´m trying to add multilines to the body, but can´t find the fix. I tried to do it with html but i don´t know how...
$Email = "x"
$Internal = "x"
$Subject = "New"
$Body = "Sending new files. Cheers!"
[array]$attachments = Get-ChildItem "\\ip\ftp$\new\Fac" *.pdf
if ([array]$attachments -eq $null) {
}
else {
$Msg = #{
to = $Email
cc = $Internal
from = "to"
Body = $Body
subject = "$Subject"
smtpserver = "server"
BodyAsHtml = $True
Attachments = $attachments.fullname
}
Send-MailMessage #Msg
}
If you want a multi-line string literal, use here-strings:
$Body = #'
Multiple
lines
go
here
'#
You can also construct a multi-line string from multiple individual strings with the -join operator:
$Body = 'Line1','Line2','Line3' -join [Environment]::NewLine
But since you want HTML, better join with <br /> instead:
$Body = 'Line1','Line2','Line3' -join '<br />'

Check CSV for object not matching?

Probably a really elementary question but preliminary searches didn't return much. I'm writing a script that takes $CSC (which is user input) compares it to a .csv object called "CSC" and then populates the relevant information based off that.
$CSC = "1100 4WWW" #Hardcoded value to test against #CSC are always <#### #ChChCh>
$roster = Import-Csv <my path>
Foreach ($row in $roster) {
If ($CSC -eq $row.CSC) {
$Department = $row.Department
$Division = $row.Division
$Street = $row.Street
$City = $row.City
$State = $row.State
$Zipcode = $row.Zipcode
$OfficePhone = $row.Phone
$Country = $row.Country
} Else { }
}
That's working fine but how would I check if a user input $CSC didn't match an in the list?
Making the else or making an elseif ($CSC -ne $row.CSC) obviously returns a value for every line except the matching one. I'm guessing I should use a nested if statement but being self taught I wasn't sure what the best way to do this is. Thanks.
I can think of a couple things you can do.
Option 1: Using the -match operator. [not recommended as it has some regex constraints but I will present it as an option anyway]
$CSC = "1100 4WWW" #Hardcoded value to test against #CSC are always <#### #ChChCh>
$roster = Import-Csv <my path>
if ($roster -match $CSC)
{
Foreach ($row in $roster) {
If ($CSC -eq $row.CSC) {
$Department = $row.Department
$Division = $row.Division
$Street = $row.Street
$City = $row.City
$State = $row.State
$Zipcode = $row.Zipcode
$OfficePhone = $row.Phone
$Country = $row.Country
} Else { }
}
}
else
{
#your 'not a match' code goes here
}
Option 2: Set a flag
$CSC = "1100 4WWW" #Hardcoded value to test against #CSC are always <#### #ChChCh>
$roster = Import-Csv <my path>
$flag = $false
Foreach ($row in $roster)
{
If ($CSC -eq $row.CSC)
{
$Department = $row.Department
$Division = $row.Division
$Street = $row.Street
$City = $row.City
$State = $row.State
$Zipcode = $row.Zipcode
$OfficePhone = $row.Phone
$Country = $row.Country
$flag = $true
}
Else { }
}
If (!$flag)
{
#your 'not a match' code goes here
}

How to get GET parameter?

I was successfully able to open a port on my computer (using only PowerShell) and know when HTTP requests are done to that port. I came up with this simple code:
$listener = [System.Net.Sockets.TcpListener]5566;
$listener.Start();
while ($true) {
$client = $Listener.AcceptTcpClient();
Write-Host "Connected!";
$client.Close();
}
If I open my browser and type http://localhost:5566 in the PowerShell interface it will show a message that a user got connected.
What I need to do is to get the GET parameters of this HTTP request. For example, if instead I had opened my browser and typed http://localhost:5566/test.html?parameter1=xxx&parameter2=yyy.
How can I grab the GET parameters (parameter1 and parameter2) name and values using my simplified code above?
If you are comfortable using the HttpListener instead of the TcpListener. It's easier to do the job.
Below script will output in a browser
Path is /test.html
parameter2 is equal to yyy
parameter1 is equal to xxx
Quick and dirty script
$listener = New-Object System.Net.HttpListener
$listener.Prefixes.Add("http://localhost:5566/")
try {
$listener.Start();
while ($true) {
$context = $listener.GetContext()
$request = $context.Request
# Output the request to host
Write-Host $request | fl * | Out-String
# Parse Parameters from url
$rawUrl = $request.RawUrl
$Parameters = #{}
$rawUrl = $rawUrl.Split("?")
$Path = $rawUrl[0]
$rawParameters = $rawUrl[1]
if ($rawParameters) {
$rawParameters = $rawParameters.Split("&")
foreach ($rawParameter in $rawParameters) {
$Parameter = $rawParameter.Split("=")
$Parameters.Add($Parameter[0], $Parameter[1])
}
}
# Create output string (dirty html)
$output = "<html><body><p>"
$output = $output + "Path is $Path" + "<br />"
foreach ($Parameter in $Parameters.GetEnumerator()) {
$output = $output + "$($Parameter.Name) is equal to $($Parameter.Value)" + "<br />"
}
$output = $output + "</p></body></html>"
# Send response
$statusCode = 200
$response = $context.Response
$response.StatusCode = $statusCode
$buffer = [System.Text.Encoding]::UTF8.GetBytes($output)
$response.ContentLength64 = $buffer.Length
$output = $response.OutputStream
$output.Write($buffer,0,$buffer.Length)
$output.Close()
}
} finally {
$listener.Stop()
}
Cheers
Glenn