Alternative Ways to Send Emails with PowerShell

I am facing an issue with sending emails using a PowerShell script as my company's Virus scan (McAfee) is blocking port 25. While I am aware of the option to disable the "prevent mass email" setting in McAfee and calling Outlook within the script, both options are not ideal for me. Hence, I am seeking alternative methods to send emails using PowerShell without resorting to the mentioned options.

Thank you.

 $From = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87e9e6eae2c7e9e6eae2a9e4e8ea">[email protected]</a>"
 $To = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fe909f939bbe909f939bd09d9193">[email protected]</a>"
 $Body = Test" 
 $Subject2 = "Hi"
 $SMTPServer ="smtp.com"

Send-MailMessage -From $From -To $To -SmtpServer $SMTPServer -Subject $Subject1 -Body $Body'

$Outlook = New-Object -ComObject Outlook.Application
$Mail = $Outlook.CreateItem(0)
$Mail.To = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9b7b8b4bc99b7b8b4bcf7bab6b4">[email protected]</a>"
$Mail.Subject = "Hi"
$Mail.Body = "Hello"[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$Mail.Send() '

Answer №1

Explore .NET Framework Classes

An option is to utilize .NET classes by manually creating a [MailMessage] object and sending it through the [SmtpClient] class. However, be cautious as this method might trigger issues with McAfee software similar to what Send-MailMessage does.

$From = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="adc3ccc0c8edc3cc80cdc3c5">[email protected]</a>"
$To = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2749464a426749464420474b49">[email protected]</a>"
$Body = "Test" 
$Subject2 = "Hi"
$SMTPServer ="smtp.com"

$message = New-Object System.Net.Mail.MailMessage $From, $To
$message.Subject = $Subject2
$message.Body = $Body

$smtpclient = New-Object Net.Mail.SmtpClient($SMTPServer)
$smtpclient.Send($message)
  • Find more information here

Leverage Exchange Web Services

To utilize EWS effectively, ensure you have the Microsoft.Exchange.WebServices.dll file which can typically be located in directories such as:

A sample function implementation of EWS sourced from Mike Pfeiffer's blog is provided below:

Function Send-EWSMailMessage {
  [CmdletBinding()]
  param(
    [Parameter(Position=0, ValueFromPipelineByPropertyName=$true, Mandatory=$true)]
    [Object]
    $PrimarySmtpAddress,

    [Parameter(Position=1, Mandatory=$true)]
    [System.String]
    $Subject,

    [Parameter(Position=2, Mandatory=$true)]
    [System.String]
    $Body
    )

  BEGIN {
    Add-Type -Path "C:\bin\Microsoft.Exchange.WebServices.dll"
    $sid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value
    $user = [ADSI]"LDAP://<SID=$sid>"
  }

  PROCESS {
    $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService
    $service.AutodiscoverUrl($user.Properties.mail)

    if($PrimarySmtpAddress -is [Microsoft.Exchange.Data.SmtpAddress]) {
      $Recipient = $PrimarySmtpAddress.ToString()
    } else {
      $Recipient = $PrimarySmtpAddress
    }

    $mail = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage($service)
    $mail.Subject = $Subject
    $mail.Body = $Body

    [Void]$mail.ToRecipients.Add($Recipient)
    $mail.SendAndSaveCopy()
  }

  END {
  }
}
  • Resource on Sending Email with PowerShell and the EWS Managed API

Although not tailored for PowerShell implementations, the link below provides valuable insights:

Answer №2

Does your current SMTP server have the capability for encrypted connections? If it does, you can test it with the following code:

Send-MailMessage -To $to -From $from -SmtpServer $smtp -UseSsl -Port "587"

I am unable to test this myself as I do not have McAfee installed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the proper way to raise an Exception and then handle it in code?

Is there a way to store an error message in my $message variable if an exception is thrown from the model? I have managed to pass the exception to the controller, but I am unsure of how to handle it in the view. Below is an example illustrating what I am ...

Silex: A Step-by-Step Guide to Implementing Loops in Forms

Utilizing the code snippet below, I can generate a Silex Form that includes a text field for the team name and checkboxes to add users to the team. $form = $app['form.factory']->createBuilder(FormType::class) ->add('name' ...

"Does anyone know where I can find the my.cnf or mysql.conf file on Mac OS Catalina

I am trying to locate the mysql configuration file in my system, but I couldn't find it in both /etc/my.cnf and /usr/local/mysql. Can you point me to where this file might be located? Just a note that I installed mysql using a .pkg file from the off ...

Having trouble displaying a message on the browser using PHP?

Check out my PHP code: <?php echo "hello world"; $con = mysql_connect("localhost","root","root123"); echo "Connected"; mysql_close($con); echo "hell"; ?> While it prints 'hello world', 'connected', and &apos ...

Listing products from Google Shopping Content API comes with a maximum limit set for each request. This

I've been using the code snippet below to retrieve a list of products from the Google Shopping content API. $products = $service->products->listProducts($merchantId, array('pageToken' => $nextPageToken, ...

Guide on transferring image upload form's enctype information to PHP with Ajax?

I am facing a challenge with uploading an image using PHP and AJAX. I have been experimenting with the code, but I'm unsure about how to handle the enctype data of the file being uploaded through AJAX and then passing it to PHP for saving the file pat ...

Content refuses to show up on my social networking website project when Ajax is employed

I've been working on a Social Media website for a major project, and I recently implemented Ajax to load posts. However, I'm facing an issue where the content is not displaying on the index page after implementation. My goal is to load 10 posts a ...

Sending JSON data from an Android device to a server using PHP

I am facing some issues with locating and utilizing the JSON object that my application sends to my server. Here is the code snippet: InputStream inputStream = null; String result = ""; try { // 1. create HttpClient HttpClient h ...

What mistake did I make when trying to use the Haversine formula in PHP?

I have 3 functions which seem similar but produce different results... class GeoCalculations { const EARTH_RADIUS = 6371000; public function degToRad($deg) { return $deg * pi() / 180; } public function haversineDistance($lat ...

Can we switch the country name to the database name in Jvector?

I've successfully implemented the Jvectormap application and it's functioning as expected. When I click on a country, it displays the name of that country. I have established a simple database for specific countries. Through AJAX, I've conn ...

Formatting of MySQL output is not maintained after execution via PHP

I am working on receiving formatted output from MySQL as it usually appears when executed from a shell. I have found some discussions about this topic here and here, but unfortunately, the solutions are not effective in my case. For example, if I execute ...

Validate the date and time in the URL using PHP

The URL should contain the date and time in the format YYYY-MM-DD-HH-II-SS. I need to validate its correctness before inserting it into a MySQL database column with a timestamp format. 1) Using $timestamp = $this->input->get('time_from'), ...

Finding all URL and titles using regex

I am looking to extract both the URLs and titles from a block of text. Les <a href="http://test.com/blop" class="c_link-blue">résultats du sondage</a> sur les remakes et suites souhaités sont <a href="http://test.com" class="c_link-blue"& ...

Tips on incorporating background color into HTML emails dispatched via PHP mail()

Struggling to add a background color to my HTML email. I've attempted various methods: Inserting <script> tags with CSS code inside Adding bgcolor in body tags Using a CSS style sheet All to no avail. I suspect it could be the email provi ...

PHP Dropdown list conundrum: seeking assistance

Hello, I am new to stackoverflow and seeking assistance for my first question I am looking to create a select box or drop down list using PHP code like this: <?php $i = 0; ?> <?php $orders = osc_list_orders(); ...

Access Denied Issue with nginx+php-fpm despite directory being set to 777

I encountered the following error: Despite setting my folder permissions to 777 and assigning ownership to nginx, I am still getting a permission denied issue with php-fpm running as nginx. Warning: error_log(/var/www/vhosts/example.com/httpdocs/includes ...

Sharing an update on my wall

Looking for a way to customize wall posts on my Facebook Application Profile Page, as the existing "Post to Wall" functionality doesn't post the pictures I want. I'm in need of a PHP script that can help me achieve this: Inputs: App ID (ID ...

Preventing the submission of form post values by using jQuery remote validation

     Within my form, I have incorporated two submit buttons (save & exit, next) and implemented remote email address duplication checks. Everything is functioning properly, however, upon submission of the form, I am unable to determine which specific s ...

Employing strtotime to locate the date preceding a specific date

Hey there, I've got a quick question that has been puzzling me lately. I have a specific date, like "first Sunday in April," and I'm trying to figure out the day before using the strtotime function in PHP. I thought about how this task would be m ...

Using jQuery code within PHP pages is a convenient and powerful way to

I am currently facing an issue with PHP and jQuery. Here is the structure of my website: header.php - contains all css and js files. index.php - main page. sidemenu.php - includes the side menu in index.php Within sidemenu.php, I have the following JS ...