Выполнение команды powershell для отправки электронной почты на программе c exe не работает

Here it works. So now I want to use this code on a private way (avoiding showing passwords and emails).

So I made a console app with C# to open Powershell and execute the command, but it’s not working.

I’m not receiving any errors on visual studio. if I open .exe it closes inmediatly as if it would be working. But no email is sent or received.

I want to do it by this way because of the privacy the command would have avoiding passwords and emails being shown. Program has to activate when X conditions on computer happen, so it has to execute easy.
Say that if I execute the command on CMD, i receive a different error, that’s why I’m doing it on powershell.

Send-MailMessage command

To send emails the simplest way is to use the command. The method documentation looks like this:

Each bracket contains an argument that can be passed to the command. To use the command to send email in Powershell we must first obtain access to an SMTP mailserver. The SMTP server will receive our mail send request and send the email to the desired destination using the SMTP protocol. Normal mail clients tend to use IMAP and POP3 but pretty much ever server will support SMTP so check with your provider.

Powershell reads a variable for SMTP access when you send emails called . Set this value before sending like so:

Or by passing arguments to the send command:

Composing emails with Powershell

To send an email with Powershell include your destination recipients and a message body. A simple message might look like this:

Send attachments with Powershell

You can read files with Powershell and attach them to your email by creating a new object with the file path. Here is an example
script showing how to include files in your email.

When not to use Powershell (security concerns)

Powershell is great but has some drawbacks when sending emails. According to Microsoft the Send-MailMessage is obsolete and no longer recommended as it cannot guarantee secure connections. For that reason it is important to consider some alternatives such as the free Powershell package MailSlurp. Running Send-MailMessage confirms this by printing the warning below:

Alternative methods for sending email in Powershell

A great way to send emails in Powershell without using the Send-MailMessage command is by using a free and secure email API service like MailSlurp. MailSlurp offers SMTP mail servers with custom API access so you can send and receive emails in any scripting environment using secure connections. The first step is to sign up and obtain a free API Key.

Then create a new inbox email address to send emails with. Save the inbox ID as this is important for the next step:

Send email using Invoke-WebRequest

To send an email using MailSlurp simply make an HTTP/S POST request and pass the message parameters as JSON:

Running the script returns a 201 status code if successful.

Conclusion and next steps

Powershell is a great way to automate tasks including the sending of emails and attachments. Use the command to send emails and attachments using your own SMTP server. If you don’t have one or need a more secure solution use an email API service like MailSlurp and the method to send your payload.

To take your scripting to the next level consider using the official MailSlurp library package on Nuget to write email automation in CSharp and F# instead.

Do I specifically need an outlook or gmail account?

That was a really useful link, thanks!

Was the top google result, good luck

I searched and didn’t see that link, I’ll blame my company laptop having Edge installed for that.

To send via Gmail yes you need a Gmail account, to send to Gmail no you just need an account with whatever mail server you want to use instead of Gmail.

Note this library is obsolete, not recommended:https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/send-mailmessage

The Send-MailMessage cmdlet is obsolete. This cmdlet doesn’t guarantee secure connections to SMTP servers. While there is no immediate replacement available in PowerShell, we recommend you do not use Send-MailMessage.

MailKit is preferred https://www.powershellgallery.com/packages/Send-MailKitMessage/

Can you use a rack space email?

You need to ask your provider what email-related clients are supported. These are things like POP3, IMAP, Exchange, and so on. Not PowerShell. PowerShell just provides a way for you to run things and then those things would then talk to those email client stuff.

For example, if Rackspace allows IMAP, they’ll give you a hostname, port (or default port or whatever), and then client credentials on how to log onto your account. Or it is something you turn on yourself and it spits out these at you.

How would I turn it on myself and get it “spat out”? Thank you for your response.

Provider documentation for the turning it on yourself part. I don’t know how Rackspace does it. They’re your provider. You gotta figure out that part yourself with their help 🙂

:/>  Настройка AMD Radeon Software Adrenalin 2020 Edition -

Spat out is just slang for “the provider says go punch in these values for these fields”

If Rackspace says “my IMAP address is BruceWayneIsNotBatman”, you’d use that value wherever your IMAP tool asks for that address. If Rackspace says your port is 993, you’d put that in wherever your tool asks for the port number. We’re assuming Rackspace is cool and tells you stuff. If they don’t, hunt down documenation sorta like what u/jurassic_pork did.

Thank you for the response.

Risk depends on the situation. I think Send-MailMessage is ok for sending low risk notification emails from a PowerShell process to an IP whitelisted mail inhouse smtp server.

Really all you need is an SMTP server, and maybe a login to the server.

$EmailSubject = “Subject_of_Email”

$SMTPServer = “smtpServer.emailProvider.com”

$SMTPPort = “25” $Body = “Test that you want to include in the email”

$Message = New-Object Net.Mail.MailMessage($EmailFrom, $EmailTo, $EmailSubject, $EmailBody)

$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, $SMTPPort)

Note that all of this would be in plain-text, use SSL/TLS for anything that requires security.

You can use HTML formation for the Body, but I don’t remember the exact way to do that. But, you are correct, this would be more for plain text with no security.

If you have Exchange Online and you want to send emails from your tenant, use the Graph API.

in a professional setting, either connect to the mail server, or use something like sendgrid.

Another way is to use the PS Module called Mailozaurr

The simplest script to send an email with PowerShell

Let’s start with simple things. Here is a one-line script based on the Send-MailMessage cmdlet you can use right now to send an email from PowerShell using SMTP protocol.

Send-MailMessage -To ” -From ” -Subject ‘Your message subject’ -Body ‘Some important plain text!’ -Credential (Get-Credential) -SmtpServer ” -Port 587

All you need is to insert the email address of a sender and a recipient, as well as specify the SMTP server you’re going to use. Then copy-paste this script to your PowerShell and press enter.

We cover the process of writing the one-line script in detail in our Mailtrap tutorial:

To check if the code works properly, you can send a test email to a virtual inbox. For this, you need a proper email-testing solution, such as Mailtrap Email Sandbox belonging to the Mailtrap Email Delivery Platform.

Выполнение команды powershell для отправки электронной почты на программе c exe не работает

To send a test email to Email Sandbox, this is the script you can use:

Here, we’ve just specified the SMTP host. The addresses of the recipient and the sender are not real, as you might have guessed. And that’s one of the benefits of using an email testing solution – you don’t have to deal with an actual email to test the email workflow.

Выполнение команды powershell для отправки электронной почты на программе c exe не работает

Enter the credentials using the pop-up window and continue. Soon after that, the test email should appear in your virtual inbox.

For full instructions on how to send test emails from PowerShell using Mailtrap, watch our dedicated tutorial:

Alternatively, you can use a dummy email, but that can be poor testing practice. Learn why in our blog post Why Using Dummy Email for Testing Just Doesn’t Work.

Can I send an HTML email or an email with attachments from PowerShell to multiple recipients?

Yes you can! Send-MailMessage lets you pump up your email with many parameters, including HTML content, priority, and so on. Also, you can send emails to multiple recipients by specifying them in the corresponding parameter. Here is what you can make use of:

-To Email address of a recipient or recipients

-Bcc Email address of a BCC recipient or recipients

-Cc Email address of a CC recipient or recipients

-From Sender’s email address

-Subject Email subject

-Body Email body text

-BodyAsHtml Defines that email body text contains HTML

-Attachments Filenames to be attached and the path to them

-Credential Authentication to send the email from the account

-SmtpServer Name of the SMTP server

-Port Port of the SMTP server

-DeliveryNotificationOptionThe sender(s) specified in the Form parameter will be notified on the email delivery. Here are the options:None – notifications are off (default parameter) OnSuccess – notification of a successful delivery OnFailure – notification of an unsuccessful delivery Delay – notification of a delayed deliveryNever – never receive notifications

-Encoding The encoding for the body and subject

-Priority Defines the level of priority of the message. Valid options are:Normal (default parameter)LowHigh

-UseSsl Connection to the SMTP server will be established using the Secure Sockets Layer (SSL) protocol

So, let’s make a script that will send an email containing HTML text and an attachment. This time, we’ll define the parameters in advance and then refer to them in the Send-MailMessage cmdlet:

As you noticed, we used $Body += to add a new line to the body text of the message.

You can now preview how this email looks and do an analysis of its HTML/CSS using Mailtrap Email Sandbox’s HTML Check feature. This feature gives you insight into the support top email clients have for the HTML elements and CSS rules used in your emails.

:/>  Как проверить качество соединения через командную строку

For any unsupported or partially supported elements/rules, it will provide a list of email clients facing the issue as well as a link to the line of code containing the element/rule.

Start testing your PowerShell emails for free.

Send an email from PowerShell using Mailtrap Email API

The Mailtrap email delivery platform also comes with an email-sending solution called Mailtrap Email Sending you can use to send your emails to real recipients from PowerShell or any other app.

Email API provides a sending throughput of up to ~10,000 emails/second but also more control over email deliverability thanks to its actionable analytics features.

Using these actionable analytics features consisting of deliverability alerts, 60-day email logs, dashboards with critical metrics, and webhooks, you can find and fix sending issues very early on.

What’s more, if you really want to dig deeper into your email performance, you can filter the performance stats. Mailtrap categorizes email performace data by email category, mailbox provider, and/or domain.

Выполнение команды powershell для отправки электронной почты на программе c exe не работает

Other features of Mailtrap Email Sending include dedicated IPs, auto IP warmup, and suppression lists, just to name a few.

So, how does the sending process work?

First, add and verify a domain under Sending Domains in your Mailtrap account, as described in this knowledge base article.

Then, to send with Mailtrap in Windows PowerShell, first choose one of the sending streams Transactional or Bulk. Afterward, decide whether you will be using SMTP or API and find the necessary credentials under your selection.

Выполнение команды powershell для отправки электронной почты на программе c exe не работает

Example code for sending via API:

Example code for sending via SMTP:

Send-MailMessage -To “” -From “” -Subject “Your message subject” -Body “Some important plain text!” -Credential (Get-Credential) -SmtpServer “” -Port 587 -UseSsl

For full instructions on how to send emails from PowerShell using the Mailtrap Email Sending email API, watch our dedicated tutorial:

Send an email from PowerShell using the Gmail SMTP server

In case you want to send emails via Gmail’s SMTP server, simply add smtp.gmail.com as the SMTP host.

We made an attempt and filled in the credentials in the pop-up window. But the server replied with an error – 551 Authentication Required. To fix this issue, you need to turn on the Less secure app access in the Security tab of your Google Account. We did it, and PowerShell successfully delivered our message to the destination. Discover more about SMTP response codes and commands in our dedicated blog post.

For full instructions on how to send emails from PowerShell using the Gmail SMTP, watch our dedicated tutorial:

SMTP settings for popular email providers

Windows Live Hotmailsmtp.live.com58725TLS

Send emails from PowerShell using EASendMail

EASendMail is an SMTP component that supports such protocols as SMTP, ESMTP (extended SMTP), EWS (Exchange Web Service), and WebDAV (Web Distributed Authoring and Versioning) protocols. The component is mostly used to send emails in COM/.NET/.NET Core environment applications and apps built with:

Also, you can use EASendMail to send emails from PowerShell. Here is a guide for this in the unlikely event that you will need it:

In the code above, we used Email Sandbox SMTP credentials, and that is why the email ended up there. You can, of course, change this according to your needs.

For full instructions on how to send emails from PowerShell using EASendMail, watch our dedicated tutorial:

Mass mailing from PowerShell using EASendMail Service Queue

For full instructions on how to send mass emails from PowerShell, watch our dedicated tutorial:

Send emails from PowerShell using System.Net.Mail API

Alternatively, you can use the .Send method and modified syntax like this one:

PowerShell is a great tool to automate tasks and create reports or exports, but at some point, you want to send an email with PowerShell. Maybe when a task failed or too automatically email the report.

For sending emails with PowerShell we could always rely on the send mailmessage cmdlet. But this cmdlet is obsolete now and Microsoft recommends not to use it anymore. So what is currently the best way to send emails with PowerShell?

In this article

In this article, we will look at the alternatives for the Send-MailMessage cmdlet in PowerShell to send email.

Send-MailMessage Obsolete

To send email from PowerShell we could always use the Send-MailMessage cmdlet. This cmdlet allows you to send emails including attachments from an SMTP server that you specify. The problem with the send mailmessage cmdlet is that it doesn’t support modern protocols and authentication.

This means that you can’t use it anymore in combination with Exchange Online for example. You could, however, still use it with other SMTP servers that don’t require a secure connection.

Microsoft isn’t updating the Send-MailMessage cmdlet at the moment. But there are a couple of alternatives that we can use to send emails. We will focus on 3 methods:

:/>  Как загрузить файл по url-адресу в power shell

Using PnPOnline module – Send-PnPMail

The Send-PnpMail method uses Microsoft Graph in the background. When you install and register the PnPOnline module, the required permissions are automatically added to the enterprise application that is created in Azure. It’s also possible to use the Exchange Online server directly, but then you are limited to internal email only.

A downside of the Send-PnPMail module is that you can’t add attachments to your emails. So keep that in mind. Also, it requires at least PowerShell 7, which isn’t installed by default on Windows 2022 for example.

Sending email with Send-PnPMail

To simply send an email you will need to specify the From and To address, subject, and body of the email:

The email will be saved in the send items of the mailbox you specified to send from. This method will work for sending emails to both internal and external recipients.

If we look at the documentation of the Send-PnPMail cmdlet then the content type of the body should be HTML by default. However, during my tests, I noticed that HTML wasn’t parsed correctly. Only after I set the BodyContentType parameter to true was HTML supported:

In the example above I am using splatting to configure the parameters for the Send-PnPMail cmdlet. This makes it easier to read and change the parameters.

Send Mail with Microsoft Graph

The new recommended way by Microsoft to send email with PowerShell is to use Microsoft Graph. The PnPOnline, that we looked at earlier, uses Graph in the background. But we can also use Microsoft Graph directly to send emails.

So the first step is to connect to Microsoft Graph with the scope Mail-Send:

Connect-MgGraph -Scopes “Mail.Send”

Sending an email with Graph isn’t as straightforward as with PnPOnline or the old Send-MailMessage cmdlet. We will first need to create a hashtable with all the email parameters and body that we want to send:

Adding Attachments to Send-MgUserMail

Additionally, we can only send attachments up to 3Mb file size. If you want to send larger attachments you will first need to create a draft email, upload the attachment, and then call the send action.

Using Mailozaurr to Send Email in PowerShell

Mailozaurr is a third-party PowerShell module that aims to provide an easier way to send emails from PowerShell. It supports multiple methods to send emails, including Microsoft Graph, SMTP with oAuth2, and SendGrid API.

To send emails with Mailozaurr, we still need to create a secure connection with the Exchange Online server. There are a couple of ways to do this, but one of the easiest ways to do this is to use an Azure Enterprise Application with the Mail.Send permissions.

Step 1 – Creating Azure Enterprise Application

So the first step is to create an application in Azure with the correct permissions. You can also use an exting application for this, but it’s best to use an Azure Enterprise Application for a single purpose. This will make managing credentials a lot easier later on.

To use the newly created application, we will need the Application ID, Directory (tenant) ID, and the Secret Value. The first two can be found in the overview of the application:

We will need to create the client secret, click on Certificates & secrets, and click on New Client Secret. Give the client secret a new one, set an expiration date, and click on Create. Write down the Value.

Step 2 – Create a Credential Object

With the application created, we can now continue in PowerShell to send an email. We first need to create a credential object with the IDs and Secret Value that we have created:

$appId = “8949e1fa-1234-4301-a006-32bdf6f09791”
$tenantId = “11e55098-1234-5467-aabb-123456789la”
$secretValue = “Tet8Q~ASDKhjln1321_asdnj0123enlazy”

$Credential = ConvertTo-GraphCredential -ClientID $appId -ClientSecret $secretValue -DirectoryID $tenantId

You can store the value of $secureSecret in your script.

Step 3 – Send Mail with Mailozaurr

Adding attachments has also become a lot easier with the Mailozaurr module. Simply specify the path(s) to the attachments that you want to add to the email. You are not limited to the 4MB file size limit anymore. If the attachment is bigger, then the Mailozaurr module with take care of it.

Wrapping Up

Sending emails with PowerShell has become a bit more work compared to the old Send-Mailmessage cmdlet. The PnPOnline method is pretty easy to implement and use. But if you want more options and control, then the Mailozaurr module is a great option.

It does however takes a little bit of work to set up correctly, but ones you have configured the permissions and authentication then it’s the best option to send emails with PowerShell.

I hope you like this article, if you have any questions, just drop a comment below.