How to split email addresses with ; in a qw - perl

my #TeamRecipients = qw(
mike#domain.com
john#domain.com
ken#domain.com
rajah#domain.com
);
sub sendEmailToTeam
{
my ($title, $msg) = #_;
my $email = new Common::Email(
'Sender' => 'rajah#domain.com',
'To' => \#TeamRecipients,
'Subject' => $title,
'Message' => $msg
);
if (not $ENV{'NIGHTLY_RUN_DEBUG_MODE'})
{
$email->send();
}
}
In the code above, the domain is my company name and individual team members are receiving emails without any issue but they can't reply in the same thread because the email address are in combined as shown: "mike#domain.com john#domain.com ken#domain.com rajah#domain.com" , instead of "mike#domain.com; john#domain.com; ken#domain.com; rajah#domain.com"
I modified TeamRecipients to
my #TeamRecipients = qw(
mike#domain.com;
john#domain.com;
ken#domain.com;
rajah#domain.com;
);
but it didn't work. Team members didn't get the initial email either.
I also introduce a intermediate array like bellow
my #MyTeamRecipients = map { split(/;/, $_)} #TeamRecipients;
but it didn't work either.
Experts,
Is there any solutions?
Thanks,
Rajah

Use join:
'To' => join(';', #TeamRecipients),

Related

Perl read a file and send e-mail

I have a log file of below format
D12345 joe#gmail.com
C67890 mary#gmail.com
B45678 don#gmail.com
A12309 joe#gmail.com
F45670 mary#gmail.com
F45470 joe#gmail.com
Currently I'm able to send e-mail to everyone with below e-mail body content
your Product id: $product_id
($product_id is D12345, A12309, F45470 , C67890, F45670)
Problem is 'N' e-mails are sent to an user if their e-mail id is present N times in the log file.
Example :
2 e-mails are sent to mary#gmail.com and 3 e-mails are sent to joe#gmail.com
I want to send only one e-mail to the users but having all their product ids, if single e-mail id occurs multiple times in the output file, like
your Product ids: C67890, F45670 to mary#gmail.com
and
your Product ids: D12345, A12309, F45470 to joe#gmail
My current code snippet
open my $fh, '<', "output.txt" or die "could not open file: $!";
while (my $line = <$fh>) {
my ($product_id, $to_email) = $line =~ /(\w\d+)\t(\S+)/;
my $MailFrom = 'myemail#domain.com';
my $subject = "PRODUCT ID DETAILS";
my $message = "your Product ids: $product_id";
%mail = (
To => $to_email,
From => $MailFrom,
Subject => $subject,
Message => $message
);
$mail{Smtp} = 'mail.myorg.com';
sendmail(%mail)or die $Mail::Sendmail::error;
}
close $fh;
Suggestions are really appreciated. Thanks in advance.
You must aggregate the information from the log file into a hash before sending the mails
Here's some example code which dumps the %mail hash instead of calling sendmail so that you can see the results
use strict;
use warnings 'all';
use Data::Dump;
my %users;
{
open my $fh, '<', "output.txt" or die "could not open file: $!";
while ( <$fh> ) {
my ($prod, $user) = split;
push #{ $users{$user} }, $prod;
}
}
# Convert arrays of product codes into comma-separated strings
#
$_ = join ', ', #$_ for values %users;
while ( my ($user, $prods) = each %users ) {
my %mail = (
To => $user,
From => 'myemail#domain.com',
Subject => 'PRODUCT ID DETAILS',
Message => "Your product IDs: $prods",
Smtp => 'mail.myorg.com',
);
dd \%mail
#sendmail(%mail) or die $Mail::Sendmail::error;
}
output
{
From => "myemail\#domain.com",
Message => "Your product IDs: D12345, A12309, F45470",
Smtp => "mail.myorg.com",
Subject => "PRODUCT ID DETAILS",
To => "joe\#gmail.com",
}
{
From => "myemail\#domain.com",
Message => "Your product IDs: B45678",
Smtp => "mail.myorg.com",
Subject => "PRODUCT ID DETAILS",
To => "don\#gmail.com",
}
{
From => "myemail\#domain.com",
Message => "Your product IDs: C67890, F45670",
Smtp => "mail.myorg.com",
Subject => "PRODUCT ID DETAILS",
To => "mary\#gmail.com",
}
This is not a perl question, just how to do basic coding.
I would preprocess the data to fit your needs i.e. create a hash of arrays using the email id as the key and push the product into the array.
You will end up with something like:
{
joe#gmail.com: ['D12345', 'A12309', 'F45470'],
mary#gmail.com: ['C67890', 'F45670'],
don#gmail.com: ['B45678']
}
Once you've created that data structure form your log file it should be simple enough the iterate over each key and create an email with the values.

How to loop through subarrays of a SOAP::Lite response in Perl?

I have a Perl script that is successfully getting a response from my ShoreTel Phone server. The server provides information on what calls are currently connected for the extension entered. However I am having issues looping through the sub arrays to get more than one response when there are multiple items. In this case I want to get each of the caller IDs that is currently connected.
My SOAP:LITE request is successfully pulling data from the server using the following code:
use strict;
use warnings;
use SOAP::Lite;
use CGI;
use Data::Dumper;
my $myWebService = SOAP::Lite
-> uri('http://www.ShoreTel.com/ProServices/SDK/Web')
-> proxy('http://10.1.##.##:8070/ShoreTelWebSDK/WebService')
-> on_action(sub {sprintf '%s/ShoreTelWebService/%s', $_[0], $_[1]});
my $query = new CGI;
my $ip = $query->remote_host; # IP address of remote party...use later as unique identifier
my $myClientID = $query->param('MyClientID'); # Possible client ID from previous script passed into us.
my $extnNr = $query->param('MyExtn'); # Has to be at least an extension number so we know who to status.
my $url = CGI::url(-path_info=>1); # What is my URL?
# There should be an extension number given, else what would we status.
if (defined($refreshNr) && defined($extnNr) && ($extnNr ne '') && ($refreshNr ne ''))
{
# If there is a client ID defined, use it...otherwise registering and getting a client ID
# is the first thing we need to do when using our web service.
unless (defined($myClientID))
{
# To use our service, we need to register ourselves as a client...use remote IP address
# as a unique name for association to this session.
my $regClientResult = $myWebService->RegisterClient(SOAP::Data->name('clientName' => $ip));
if ($regClientResult->fault)
{
print '<p>FAULT', $myClientID->faultcode, ', ', $myClientID->faultstring;
}
else
{
# Retrieve client ID which we will be using for subsequent communication.
$myClientID = $regClientResult->valueof('//RegisterClientResponse/RegisterClientResult/');
}
}
if (defined($myClientID))
{
# Use our web service to open the line. This is necessary to get a line ID.
# print '<br>Client ID ', $myClientID, ' has been registered.<br>';
my $openResult = $myWebService->OpenLine(SOAP::Data->name('clientHandle' => $myClientID), SOAP::Data->name('lineAddress' => $extnNr));
my $lineID = $openResult->valueof('//OpenLineResponse/OpenLineResult/lineID/');
my $lineType = $openResult->valueof('//OpenLineResponse/OpenLineResult/lineType/');
my $lineName = $openResult->valueof('//OpenLineResponse/OpenLineResult/lineName/');
my $lineState = $openResult->valueof('//OpenLineResponse/OpenLineResult/lineState/');
# Call GetActiveCalls to see if anything is going on with this line.
my $result = $myWebService->GetActiveCalls(SOAP::Data->name('clientHandle' => $myClientID), SOAP::Data->name('lineID' => $lineID));
my $callID = $result->valueof('//GetActiveCallsResponse/GetActiveCallsResult/ShoreTelCallStateInfo/callInfo/callID/');
if ($callID ne '')
{
# print '<br>Call ID is ', $callID;
my $isExternal = $result->valueof('//GetActiveCallsResponse/GetActiveCallsResult/ShoreTelCallStateInfo/callInfo/isExternal/');
my $isInbound = $result->valueof('//GetActiveCallsResponse/GetActiveCallsResult/ShoreTelCallStateInfo/callInfo/isInbound/');
my $callReason = $result->valueof('//GetActiveCallsResponse/GetActiveCallsResult/ShoreTelCallStateInfo/callInfo/callReason/');
my $connectedID = $result->valueof('//GetActiveCallsResponse/GetActiveCallsResult/ShoreTelCallStateInfo/callInfo/connectedID/');
my $connectedIDName = $result->valueof('//GetActiveCallsResponse/GetActiveCallsResult/ShoreTelCallStateInfo/callInfo/connectedIDName/');
my $callerID = $result->valueof('//GetActiveCallsResponse/GetActiveCallsResult/ShoreTelCallStateInfo/callInfo/callerID/');
my $callerIDName = $result->valueof('//GetActiveCallsResponse/GetActiveCallsResult/ShoreTelCallStateInfo/callInfo/callerIDName/');
my $calledID = $result->valueof('//GetActiveCallsResponse/GetActiveCallsResult/ShoreTelCallStateInfo/callInfo/calledID/');
my $calledIDName = $result->valueof('//GetActiveCallsResponse/GetActiveCallsResult/ShoreTelCallStateInfo/callInfo/calledIDName/');
my $callState = $result->valueof('//GetActiveCallsResponse/GetActiveCallsResult/ShoreTelCallStateInfo/callState/');
my $callStateDetail = $result->valueof('//GetActiveCallsResponse/GetActiveCallsResult/ShoreTelCallStateInfo/callStateDetail/');
# Print call information.
print <<EndOfCallInfo;
HTML CODE
EndOfCallInfo
}
else
{
print <<EndOfCallInfo2;
HTML CODE
EndOfCallInfo2
}
}
}
But I am only able to access the first result in the multidimensional array.
I have tried looping through the results using
for my $t ($result->result({ShoreTelCallStateInfo}{callInfo}')) {
print $t->{callerID} . "\n";}
But I am getting absolutely no results. It appears that the the loop is not even entered.
The following code I have works fine, but only pulls the first caller ID, in this case 1955.
my $callerID = $result->valueof('//GetActiveCallsResponse/GetActiveCallsResult/ShoreTelCallStateInfo/callInfo/callerID/');
What can I do to make my loop work?
So that you can see what I am receiving from the server I have included the response from the SOAP Server using DUMP :
$VAR1 = { 'ShoreTelCallStateInfo' => [
{ 'callStateDetail' => 'Active',
'callState' => 'OnHold',
'callInfo' =>
{ 'callerIDName' => 'Joel LASTNAME',
'callID' => '69105', 'lineID' => '3947',
'connectedIDName' => 'VM-Forward',
'calledID' => '2105',
'callerID' => '1955',
'isInbound' => 'false',
'calledIDName' => 'VM-Forward',
'callReason' => 'None',
'callUniqueID' => '1369702515',
'connectedID' => '2105',
'isExternal' => 'false',
'callGUID' => '{00030000-66C2-537E-3FD8-0010492377D9}'
}
},
{ 'callStateDetail' => 'Active',
'callState' => 'Connected',
'callInfo' =>
{ 'callerIDName' => 'LASTNAME Joel ',
'callID' => '71649',
'lineID' => '3947',
'connectedIDName' => 'LASTNAME Joel ',
'calledID' => '1955',
'callerID' => '+1385#######',
'isInbound' => 'true',
'calledIDName' => 'Joel LASTNAME',
'callReason' => 'None',
'callUniqueID' => '1117287558',
'connectedID' => '+1385#######',
'isExternal' => 'true',
'callGUID' => '{00030000-66C5-537E-3FD8-0010492377D9}'
}
}
]
};
Just a guess...
The following code I have works fine, but only pulls the first caller
ID, in this case 1955.
my $callerID = $result->valueof('//GetActiveCallsResponse/GetActiveCallsResult/ShoreTelCallStateInfo/callInfo/callerID/');
What can I do to make my loop work?
SOAP::Lite docs say:
valueof()
Returns the value of a (previously) matched node. It accepts a node
path. In this case, it returns the value of matched node, but does not
change the current node. Suitable when you want to match a node and
then navigate through node children:
$som->match('/Envelope/Body/[1]'); # match method
$som->valueof('[1]'); # result
$som->valueof('[2]'); # first out parameter (if present)
The returned value depends on the context. In a scalar context it will
return the first element from matched nodeset. In an array context it
will return all matched elements.
Does this give the behavior you expect? It imposes list context on the valueof method.
for my $callerID ($result->valueof('//GetActiveCallsResponse/GetActiveCallsResult/ShoreTelCallStateInfo/callInfo/callerID/')) {
...
# do something with each callerID
}
or
my #callerIDs = $result->valueof('//GetActiveCallsResponse/GetActiveCallsResult/ShoreTelCallStateInfo/callInfo/callerID/');

How do I use the Adapative Payments "ConvertCurrency" API in Perl?

How can you convert from multiple currencies, using the PayPal API (Adaptive Payments) system? The documents only have stuff for Ruby, iOS, PHP, Rails etc... but not Perl!
https://developer.paypal.com/docs/classic/api/adaptive-payments/ConvertCurrency_API_Operation/
This is only meant as a guideline (to run in command line). It will run via the browser, but you need to add in a header (otherwise it'll give a 500 Internal Server Error)
The perl code is as follows:
currency.cgi
#!/usr/bin/perl
use warnings;
use strict;
use HTTP::Request::Common;
use LWP::UserAgent;
my $user = 'your PayPal API username';
my $password = 'your PayPal API password';
my $signature = 'your PayPal API signature';
my $application_id = 'APP-80W284485P519543T'; # this is the sandbox app ID... so you would just change this to your own app-id when going live
my #currencies = qw/GBP EUR CHF USD AUD/; # Enter all the currency codes you want to convert here
my $url = 'https://svcs.sandbox.paypal.com/AdaptivePayments/ConvertCurrency'; # remove the "sandbox." part of this URL, when its ready to go live...
my $ua = LWP::UserAgent->new();
my $headers = HTTP::Headers->new(
'X-PAYPAL-SECURITY-USERID' => $user,
'X-PAYPAL-SECURITY-PASSWORD' => $password,
'X-PAYPAL-SECURITY-SIGNATURE' => $signature,
'X-PAYPAL-APPLICATION-ID' => $application_id,
'X-PAYPAL-DEVICE-IPADDRESS' => $ENV{REMOTE_ADDR},
'X-PAYPAL-REQUEST-DATA-FORMAT' => 'JSON',
'X-PAYPAL-RESPONSE-DATA-FORMAT' => 'JSON'
);
foreach (#currencies) {
print qq|\nGetting exchange rates for $_.... \n|;
my ($status,$vals) = get_converted_amounts($_);
if ($vals->{error}) {
print qq|There was an error: $vals->{error}\n|;
exit;
} else {
print qq|Got conversion rates of:\n|;
foreach (#currencies) {
if ($vals->{$_}) {
print qq|\t$_ => $vals->{$_}\n|;
}
}
}
}
sub get_converted_amounts {
my ($currency_from) = #_;
my #currencies_to_grab;
foreach (#currencies) {
next if $_ eq $currency_from; # We dont wanna bother asking it to convert from this currency, into this currency =)
push #currencies_to_grab, $_;
}
my $json_var = {
requestEnvelope => {
detailLevel => "ReturnAll",
errorLanguage => "en_US",
},
baseAmountList => [{ 'currency' => { 'code' => $currency_from, 'amount' => 1 } }],
convertToCurrencyList => [{ currencyCode => \#currencies_to_grab }]
};
use JSON;
my $new_json = JSON::to_json($json_var);
my $request = HTTP::Request->new( 'POST', $url, $headers, $new_json );
my $response = $ua->request( $request );
my $json_returned = decode_json($response->decoded_content);
if ($json_returned->{error}[0]) {
return (0, { error => "There was an error: $json_returned->{error}[0]->{message} ($json_returned->{error}[0]->{errorId}) " });
}
my $vals;
foreach (#{$json_returned->{estimatedAmountTable}->{currencyConversionList}[0]->{currencyList}->{currency}}) {
$vals->{$_->{code}} = $_->{amount};
}
return (1,$vals);
}
Running it:
You would simply run it via SSH/Telnet, with:
perl /path/to/script/currency.cgi
You can play around with the currency codes (be sure to only use the currencyCode values found here: https://developer.paypal.com/docs/classic/api/adaptive-payments/ConvertCurrency_API_Operation/, as these are the only ones that are supported)
Although this converts from a given currency into the other related currencies (good if you want to run the script every couple of hours, and store the conversion rates) - it wouldn't be hard to tweak it so you can do:
convert(from_currency,to_currency,amount)
Hopefully this will save someone a bit of time (as I spent almost a day trying to get this going)

Perl mechanize script no form defined

I'm getting an error No form defined at cqSubmitter.pl at line 33 which is the second set_fields method. Other times I get an Error POSTing http://micron.com Internal Server Error at line 39 , which corresponds to the last click_button line.
I'm not really sure what's going on, and why it's saying no form defined? The first half of the code which includes the first click_button method works fine and saves the correct page, but when I try set_fields for the second time, it errors out.
Anyone familiar with the Mechanize package realize what's going on here?
use Data::Dumper;
use HTTP::Request::Common qw(GET);
use WWW::Mechanize;
#Prepopulated information
my $types_ = "";
my $dept_ = "";
my $group_ = "";
#Create new WWW::Mechanize object
my $mech = WWW::Mechanize->new( 'ssl_opts' => { 'verify_hostname' => 0 } );
my $url = "http://f2prbrequest";
#Fetch URL or Die Tryin'
$mech ->get($url);
$fname = "user";
$pswd = "password";
#Login to ClearQuest form using credentials
$mech->set_fields(
USER => $fname
,PASSWORD => $pswd
);
$mech->click_button(
name => 'Submit'
);
#Set fields and actually fill out ClearQuest Form
$mech->set_fields(
types => $types_
,dept => $dept_
,group => $group_
);
$mech->click_button(
name => 'submit1'
);
$mech->save_content("clearQuestFilled.html");

Magento mailing feature in custom script

I have created a custom script to import a bulk number of customers to magento database. What client needed is for each 100 customers import they needed a mail about whats going on and status of the importing.
So how can i use the magento mailing functionality so that i can create a template to send mail as like magento does. Please help me
I think you're looking for something along the following lines:
$store_id = $this->getStoreId();
$template = "import_script_email_template_name";
$from = Mage::getStoreConfig(self::XML_PATH_EMAIL_IDENTITY, $store_id);
$to = array( "name" => "Nick", "email" => "the#email.address" );
$template_variables = array(
"var1" => "somevalue",
"var2" => "someothervalue"
);
$mail = Mage::getModel("core/email_template");
$mail->setDesignConfig( array( "area" => "frontend", "store" => $store_id ))
->sendTransactional(
$template_name,
$from,
$to["email"],
$to["name"],
$template_variables
);
Note: This was lifted from Mage_Sales_Model_Order::sendNewOrderEmail() and hasn't been tested, but it should be more than enough to get you started. Treat it as pseudo-code :)
If you are just doing this from an import script, the PHP mail function should be more than sufficient.
Also can do the mailing functionality of ZEND
Here is the code
$mail_body = "<h3> These are ordered by you in the event - '".$customer_event."' </h3> <br/>". $email_body;
$to_email = $email;
$to_name = $customer_name;
$subject = 'Orders';
$Body = $body;
$sender_email = "info#mail.com";
$sender_name = "mail";
$html = new Zend_View();
$html->setScriptPath('app/locale/en_US/template/email/');
$html->assign('customer_name', $customer_name);
$html->assign('email', $to_email);
$html->assign('password', $password);
$html->assign('site_url', Mage::getUrl(""));
$html->assign('site_skin_url', Mage::getDesign()->getSkinUrl("images/"));
$html->assign('site_order_url', Mage::getUrl("").'Event.php?id='.$id.'&cart_id='.$cart_id);
$html->assign('site_name', 'Winecellarage');
$html->assign('site_data', $mail_body);
$Body_text= $html->render($template);
$mail = new Zend_Mail('utf-8');
$mail->setBodyHtml($Body_text);
$mail->setFrom($sender_email, $sender_name);
$mail->addTo($to_email, $to_name);
//$mail->addCc($cc, $ccname);
//$mail->addBCc($bcc, $bccname);
$mail->setSubject($subject);
try {
if($mail->send())
{
$msg .= "<p>Mail sent successfully to '$to_email' </p>";
}
}
catch(Exception $ex) {
$err .= '<p>'.$error_msg = $ex->getMessage()."</p>";
}
This one is working exactly what i wanted. So may be useful to some one.