Null valued expression - powershell

foreach ($OldAccount in $forwarderarray) {
$OldAccount.ForwardingAddress = $OldAccount.ForwardingAddress.substring(0,1).toupper()+$OldAccount.ForwardingAddress.substring(1).tolower()
$Separatorforwarderaddress = $OldAccount.UserPrincipalName.IndexOf("#") # This section truncates the SMTP address to the firstname.surname to remove the #
$LeftPartforwarderaddress = $OldAccount.UserPrincipalName.Substring(0, $Separatorforwarderaddress)
$RightPartforwarderaddress = $OldAccount.UserPrincipalName.Substring($Separatorforwarderaddress + 2)
$SeparatorOwnerAddress = $OldAccount.ForwardingAddress.IndexOf(".") # This section truncates the SMTP address to the firstname.surname to remove the #
$LeftPartOwnerAddress = $OldAccount.ForwardingAddress.Substring(0, $SeparatorOwnerAddress)$RightPartOwnerAddress =
$OldAccount.ForwardingAddress.Substring($SeparatorOwnerAddress + 2)
What is strange is the write host displays the value expected
But when I try to SMTP
Send-MailMessage -to $OldAccount.ForwardingAddress
I ge:
You cannot call a method on a null-valued expression
Can someone please help? What I am trying to achieve is to take out the email address for display purposes and to make the name start with a capital letter.
So why does this display the correct information
Write-Host "Sending message, to:"$OldAccount.ForwardingAddress

Related

powershell get specific row from a body

i'm getting some problem to get a specific row from a powershell body. HR team send email to us, a logic app get the body of email and pass it to a script that disable the user.
The body is like this:
Hi,
the following user have to be dismiss:
#mail: user1#mycompany.com
#mail: user2#mycompany.com
#mail: user2#mycompany.com
Bye
hr team
hrteam#mycompany.com
i would like to get only the specific row:
#mail: user1#mycompany.com
#mail: user2#mycompany.com
#mail: user2#mycompany.com
to do this i did a trick with following code:
$Body
$SplitBody = $Body.split("").split(" ").Split("#")
$objetbody = $SplitBody.Replace(" ","").Trim()
and i got following result:
Hi,
the
following
user
have
to
be
dismiss:
mail:
user1#mycompany.com
mail:
user2#mycompany.com
mail:
user2#mycompany.com
Bye
hr
team
hrteam#mycompany.com
after that i pass $objetbody into a foreach and loop all row(at the end of this foreach is put a break becouse it can disable HR mail). The flow work if HR sent only 1 mail to disable.
My question is there is a way to got that specific row that contains the mails?
Thanks
Here is a one-liner to output all email addresses using the .NET RegEx class:
[RegEx]::Matches( $body, '(?<=#mail:\s*)\S+' ).Value
The same can be achieved using Select-String:
($body | Select-String '(?<=#mail:\s*)\S+' -AllMatches).Matches.Value
RegEx breakdown:
(?<= ... starts a positive look behind pattern, meaning that the sub string we search for must be preceded by the given pattern, but this pattern won't be included in the result
#mail:\s* ... literal "#mail:" followed by optional whitespace
) ... ends the look behind pattern
\S+ ... any sequence of non-whitespace characters -> the email address
I kept the email address pattern simple, because correctly matching email addresses using RegEx can be hard. Anyway you propably want to do validation as a separate step so you can report invalid addresses. This can be done much simpler using the .NET MailAddress class:
$mailAddresses = [RegEx]::Matches( $body, '(?<=#mail:\s*)\S+' ).Value
foreach( $adr in $mailAddresses) {
try {
[System.Net.Mail.MailAddress]::new( $adr )
} catch {
# The MailAddress constructor throws FormatException for invalid address
Write-Error "Invalid mail address: '$adr'"
}
}
You could use a loop in addition to the -match operator and the use of the automatic variable $Matches:
foreach($line in $Body)
{
if($line -match '^#mail: (.*#.*\.[\w\d]+)')
{
$Matches[1]
}
}
From the example above, $Matches[1] would return the values for the matched capturing group:
user1#mycompany.com
user2#mycompany.com
user2#mycompany.com
If you want to keep #mail: use $Matches[0] instead.

how do i send an email through joomla

I have a system so folks can register for a class through my Joomla site (I believe it's 3.0). But from there, I would like to send folks an email filling variables from the registration. So something like:
Dear (name), thank you for registering for (class).
This is to remind you your class is tomorrow, (date), at (place).
I believe for the registration, the system uses authorize.net
How can I accomplish this?
Thanks for the help!!
You can use JFactory:getMailer like suggested in the following post. I'm copying here his code example (modified it a bit):
$subject = "Here is the subject of your message.";
$body = "Here is the body of your message.";
$user = JFactory::getUser();
$to = $user->email;
$from = array("me#mydomain.com", "Brian Edgerton");
# Invoke JMail Class
$mailer = JFactory::getMailer();
# Set sender array so that my name will show up neatly in your inbox
$mailer->setSender($from);
# Add a recipient -- this can be a single address (string) or an array of addresses
$mailer->addRecipient($to);
$mailer->setSubject($subject);
$mailer->setBody($body);
# If you would like to send as HTML, include this line; otherwise, leave it out
$mailer->isHTML();
# Send once you have set all of your options
$mailer->send();
That's all there is to it for sending a simple email. If you would like to add carbon copy recipients, include the following before sending the email:
# Add a blind carbon copy
$mailer->addBCC("blindcopy#yourdomain.com");
Another alternative is using JMail::sendMail: http://docs.joomla.org/API17:JMail::sendMail
Fetch the Mail Object:
`$mailer = JFactory::getMailer();`
Set a Sender
$user = JFactory::getUser();
$recipient = $user->email;
$mailer->addRecipient($recipient);
$mailer->setSender($sender);
Recipient
$user = JFactory::getUser();
$recipient = $user->email;
$mailer->addRecipient($recipient);
Create the Mail
$body = 'Body Text';
$mailer->isHtml(true);
$mailer->Encoding = 'base64';
$mailer->setBody($body);
Sending the Mail
$send = $mailer->Send();
if ( $send !== true ) {
echo 'Error sending email: ';
} else {
echo 'Mail sent';
}
https://docs.joomla.org/Sending_email_from_extensions

Email::MIME can't parse message from Gmail

So I'm using PERL and Email::MIME to get an email from gmail. Here is my code:
use Net::IMAP::Simple::Gmail;
use Email::Mime;
# Creat the object that will read the emails
$server = 'imap.gmail.com';
$imap = Net::IMAP::Simple::Gmail->new($server);
# User and password
$user = 'username#gmail.com';
$password = 'passowrd';
$imap->login($user => $password);
# Select the INBOX and returns the number of messages
$numberOfMessages = $imap->select('INBOX');
# Now let's go through the messages from the top
for ($i = 1; $i <= $numberOfMessages; $i++)
{
$top = $imap->top($i);
print "top = $top\n";
$email = Email::MIME->new( join '', #{ $imap->top($i) } );
$body = $email->body_str;
print "Body = $body\n";
}#end for i
When I run it, I get the following error:
can't get body as a string for multipart/related; boundary="----=_Part_6796768_17893472.1369009276778"; type="text/html" at /Library/Perl/5.8.8/Email/Mime.pm line 341
Email::MIME::body_str('Email::MIME=HASH(0x87afb4)') called at readPhoneEmailFeed.pl line 37
If I replace
$body = $email->body_str;
with
$body = $email->body;
I get the output:
Body =
(i.e. empty string)
What's going on here? is there a way for me to get the raw body of the message (->body_raw doesn't work either)? I'm okay with parsing out the body using regex
Email::MIME is not the best documented package I have ever seen.
The body and body_str methods only work on a single mime part. Mostly that would be a simple text message. For anything more complex use the parts method to get each mime component which is itself an Email::MIME object. The body and body_str methods should work on that. An html formatted message will generally have two MIME parts: text/plain and text/html.
This isn't exactly what you want but should be enough to show you what is going on.
my #parts = $email->parts;
for my $part (#parts) {
print "type: ", $part->content_type, "\n";
print "body: ", $part->body, "\n";
}

PHP mail to variable

I've searched and searched for something similar, but i think i'm not doing it right. So i will ask a question. This is very basic. My problem is as follows:
I have a multi-page form, consisting of 4 pages + 1 preview page. On the preview page, upon submitting i want the entire form data to be sent to 2 different mail adresses. One standard, and the other one, the one that the user has submitted.
So i have:
<?php
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];
?>
<?php
$email_from = 'mail#company.com';
$email_subject = "New Form submission";
$email_body = "You have received a new message from the user $name.\n".
"Here is the message:\n $message".
$to = "yourname#yourwebsite.com, $email /n";
$headers = "From: Company";
mail($to,$email_subject,$email_body,$headers);
?>
How should I insert the submitted $email variable in order for it to work?
Remove the \n
$to = 'yourname#yourwebsite.com,' . $visitor_email;
According to the mail() function documentation the $to parameter will take a comma-separated list of addresses as you have attempted, but should have no line break at the end.
Also, your variable is $visitor_email, rather than $email.
$to = "yourname#yourwebsite.com, $visitor_email";
You might also consider adding the visitor's email as a CC or BCC rather than the TO address. In that case, add it as a CC or BCC header (separated by \r\n), but you need to be cautious to be sure that the address is an email address and contains no line break characters which could be used for header injection.
// The From should be an email address
$headers = "From: company#example.com\r\n";
$headers .= "CC: $visitor_email;

DbConnectionStringBuilder does not parse when used in PowerShell

I am trying to use capabilities of DbConnectionStringBuilder for parsing connection-string-like user input. This works just fine in C#:
using System;
using System.Data.Common;
class Program
{
static void Main(string[] args)
{
var sb = new DbConnectionStringBuilder();
sb.ConnectionString = "server = 'smtp.gmail.com'; port = 587; user = you#gmail.com";
Console.WriteLine(sb["server"]);
Console.WriteLine(sb["port"]);
Console.WriteLine(sb["user"]);
}
}
Output:
smtp.gmail.com
587
you#gmail.com
But it does not work in PowerShell. Namely, this literally translated code in PowerShell
$sb = New-Object System.Data.Common.DbConnectionStringBuilder
$sb.ConnectionString = "server = 'smtp.gmail.com'; port = 587; user = you#gmail.com"
$sb["server"]
$sb["port"]
$sb["user"]
produces no output at all.
Any ideas why? How to make DbConnectionStringBuilder to work as a parser in PowerShell?
System.Data.Common.DbConnectionStringBuilder implements IDictionary. Powershell has a shorthand for dictionaries using . that allows retrieval and assignment of key/value pairs as if the key was a property:
$dict = #{}
$dict["key1"] = 'value1'
$dict.key2 = 'value2'
You can see that it is storing the entire connection string as a key/value pair instead of on the ConnectionString property this way:
$sb = New-Object System.Data.Common.DbConnectionStringBuilder
$sb.ConnectionString = "server = 'smtp.gmail.com'; port = 587; user = you#gmail.com"
$sb #formatted table of key/value pairs
The easiest way to get around this is to call the set_/get_ methods generated for properties:
$sb = New-Object System.Data.Common.DbConnectionStringBuilder
$sb.set_ConnectionString("server = 'smtp.gmail.com'; port = 587; user = you#gmail.com")
$sb["server"]
$sb["port"]
$sb["user"]
It is probably a bug (a gotcha anyway) and I will submit it soon. It looks like PowerShell does not call setters on properties of classes that implement IDictionary (as DbConnectionStringBuilder does, and it is the setter of ConnectionString that parses the string).
Here are two demos (the original and workaround):
# test 1 - does not work, presumably PowerShell invokes $sb["ConnectionString"] = .. instead of the setter
$sb = New-Object System.Data.Common.DbConnectionStringBuilder
$sb.ConnectionString = "server = 'smtp.gmail.com'; port = 587; user = you#gmail.com"
# the original string
$sb.ConnectionString
# nothing at all
$sb["server"]
$sb["port"]
$sb["user"]
# test 2 - works fine, we make PowerShell to invoke the ConnectionString property setter in this way
$sb = New-Object System.Data.Common.DbConnectionStringBuilder
$sb.PSObject.Properties['ConnectionString'].Value = "server = 'smtp.gmail.com'; port = 587; user = you#gmail.com"
# parsed and re-formatted string
$sb.ConnectionString
# parsed data
$sb["server"]
$sb["port"]
$sb["user"]
Output:
server = 'smtp.gmail.com'; port = 587; user = you#gmail.com
server=smtp.gmail.com;port=587;user=you#gmail.com
smtp.gmail.com
587
you#gmail.com
As far as the workaround is found we get for free a pretty powerful parser for connection-string-like data. Here is the demo that shows parsing of quite convoluted input:
# get the parser
$sb = New-Object System.Data.Common.DbConnectionStringBuilder
# input the string to parse using this workaround way
$sb.PSObject.Properties['ConnectionString'].Value = #'
Apostrophes = "Some 'value'";
Quotations = 'Some "value"';
Semicolons = '1; 2; 3';
Multiline = Line1
Line2
Line3;
Name with spaces = Some value;
Name with == sign = Some value;
'#
# get the parsed results
# the string: not the original but parsed and re-formatted
$sb.ConnectionString
# the data: parsed key/values
$sb | Format-Table -AutoSize -Wrap
Output:
apostrophes="Some 'value'";quotations='Some "value"';semicolons="1; 2; 3";multiline="Line1
Line2
Line3";name with spaces="Some value";name with == sign="Some value"
Key Value
--- -----
apostrophes Some 'value'
quotations Some "value"
semicolons 1; 2; 3
multiline Line1
Line2
Line3
name with spaces Some value
name with = sign Some value
$sb = New-Object System.Data.Common.DbConnectionStringBuilder
$sb.Add("server","smtp.gmail.com")
$sb.Add("port",587)
$sb.Add("user","you#gmail.com")
$sb["server"]
$sb["port"]
$sb["user"]