I've always used the cmdlet Send-MailMessage without specifying any -Credential. Now I need to send mail using the anonymous user. The workaround I've found is this piece of code
$pass = ConvertTo-SecureString "anyString"-AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "NT AUTHORITY\ANONYMOUS LOGON",$pass
Send-MailMessage -Credential $cred #...
It works, but is this the correct method to get the anonymous is and send anonymous mail?
You can send mail from any address, it just depends on whether the receiving mail server cares about whether it can verify the sending user or not.
For example if you send from anon#microsoft.com and microsoft does not have that account, OR they have SPF records to indicate whether the sending mail server is valid or not, then the receiving mail server might(not always) reject it.
Just make sure your email user actually exists and has a valid domain... and you can send from anonymous# or noreply# or whatever you want to.
Okay, from the comments we know we're dealing with an Exchange server. Whether or not it will do an anonymous relay depends on the configuration of the Recieve Connectors. But those restrictions only apply to the network connections. If you run Send-MailMessage on the Exchange server and use 'LocalHost' as your SMTPServer it didn't go through a receive connector so those restrictions don't apply.
If you have remoting enabled on the Exchange server you can use that to do a local invocation to send email without having to modify the Receive Connector configurations:
$EmailParams =
#{
To = '<Email To>'
From = '<Email From>'
Subject = '<Email Subject>'
Body = '<Email Body>'
SMTPServer = 'localhost'
}
$Scriptblock = [Scriptblock]::Create(
"Send-MailMessage $(&{$args} #EmailParams) ")
Invoke-Command -ScriptBlock $Scriptblock -ComputerName ExchangeServer
Related
I'm trying to set up email on SQL Server Reporting Services with Office 365. So I have properly configured Microsft tenant and mailbox.
For test on SQL machine I send an email using the Powershell Send-MailMessage script (details below):
$username = 'office#source.com'
$pass = get-content C:\pwd.txt | ConvertTo-SecureString #i'm have encoded password
$credentials=new-object Management.Automation.PSCredential -ArgumentList $username, $pass
$param = #{
SmtpServer = 'smtp.office365.com'
Port = 587
UseSsl = $true
Credential = $credentials
Encoding = 'utf8'
From = 'office#source.com'To = 'target#email.com'
Subject = '[TEST] subject for test'
Body = ' Testing SMTP from o365 '
}
Send-MailMessage #param
It's works OK, so the O365 and host configuration (e.g. network traffic, ports, tls) are correct.
Unfortunately, I am unable to run mails from SQL Server Reporting Services.
I'm try with difren setings of rsreportserver.config file. Part of setings below
<Configuration>
<RSEmailDPConfiguration>
<SMTPServer>smtp.office365.com</SMTPServer>
<SMTPServerPort>587</SMTPServerPort>
<SMTPAccountName>office#source.com</SMTPAccountName>
<SMTPConnectionTimeout></SMTPConnectionTimeout>
<SMTPServerPickupDirectory></SMTPServerPickupDirectory>
<SMTPUseSSL>True</SMTPUseSSL>
<SendUsing>2</SendUsing>
<SMTPAuthenticate>1</SMTPAuthenticate>
<SendUserName>AQAAANCMnd8BFdERjHo</SendUserName>
<SendPassword>RjHoAwE/Cl+sBAAAA0</SendPassword>
<From>office#source.com</From>
<EmbeddedRenderFormats>
<RenderingExtension>MHTML</RenderingExtension>
</EmbeddedRenderFormats>
<PrivilegedUserRenderFormats></PrivilegedUserRenderFormats>
<ExcludedRenderFormats>
<RenderingExtension>HTMLOWC</RenderingExtension>
<RenderingExtension>NULL</RenderingExtension>
<RenderingExtension>RGDI</RenderingExtension>
</ExcludedRenderFormats>
<SendEmailToUserAlias>False</SendEmailToUserAlias>
<DefaultHostName></DefaultHostName>
<PermittedHosts></PermittedHosts>
</RSEmailDPConfiguration>
</Configuration>
I'm reciving this error from Reporting Services:
Failure sending mail: At least one error has occurred.Mail will not be resent.
I found solution, You must add some registry values to your system:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v2.0.50727]
"SystemDefaultTlsVersions" = dword:00000001
"SchUseStrongCrypto" = dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions" = dword:00000001
"SchUseStrongCrypto" = dword:00000001
after restart OS, SSRS sends reports with Office 365 mailbox.
The issue is that the SMTP library used by SSRS is old and hasn't been updated. Forcing TLS 1.2 and Forcing it for .NET resolve the issue.
I have a PowerShell script that, after pinging a server address, uses Basic Auth to send an automated email via Task Scheduler. Microsoft has deprecated Basic Auth in Exchange Online in favor of Modern Auth, but I do not see clear directions for updating a PowerShell script to use Modern Auth.
This is an example of the Basic Auth that I need to convert.
$secpasswd = ConvertTo-SecureString “password” -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential (“user#place.com”, $secpasswd)
Send-MailMessage -SmtpServer smtp.office365.com -Port 587 -From user#place.com -To otheruser#place.com -Subject test -Body test -Credential $mycreds -UseSsl"
Can someone point me to an example of Modern Auth being used in a similar script or share what I need to do to update and run the above script?
Many Thanks!
As per the resources in my original comment.
Send-MailMessage is obsolete and no longer supported. Microsoft says this cmdlet does not guarantee a secure connection to SMTP servers. As per:
https://aka.ms/SendMailMessage
Therefore use the below:
Send-MgUserMail - MS Docs
Note: Send-MgUserMail requires a more complex parameter structure.
$EmailMessageContent=#'
<Strong> This is a Test Message</Strong><br>
Modern auth testing
'#
$params = #{
Message = #{
Subject = "Using MSGraph"
Body = #{
ContentType = "html"
Content = $EmailMessageContent
}
ToRecipients = #(
#{
EmailAddress = #{
Address = "SomeRecipientEmaiAddress"
}
}
)
}
}
Import-Module Microsoft.Graph.Users.Actions
Connect-MgGraph -Scopes Mail.Read
Send-MgUserMail -UserId 'SomeSenderEmailAddress' -BodyParameter $params
Point of note:
SMTP AUTH will still be available when Basic authentication is permanently disabled on October 1, 2022. The reason SMTP will still be available is that many multi-function devices such as printers and scanners can't be updated to use modern authentication.
See also the below for full details of the why and so on... (and more sample code):
Authenticate an IMAP, POP or SMTP connection using OAuth
Moving on from Send-MailMessage: Sending Email from PowerShell using
the Graph API
The Send-MailMessage Conundrum
Largely because of history, Exchange Online supports a wide variety of
connectivity protocols. Microsoft is making some progress to convince
customers to disable basic authentication for protocols they never
use, and has upgraded older protocols like POP3 and IMAP4 to use OAuth
2.0 for modern authentication. As discussed in this blog, tenants will need to find PowerShell scripts which call the Send-MailMessage cmdlet
and eventually upgrade the code with a more modern method to send
email.
The Send-MailMessage cmdlet depends on the SMTP AUTH protocol to send
email using basic authentication. Microsoft announced OAuth 2.0
support for SMTP AUTH in April 2020, but this doesn’t mean that an
off-the-shelf replacement cmdlet is available. Microsoft says that the
announcement “is for interactive applications to enable OAuth for IMAP
and SMTP [AUTH].” In effect, this means mail clients or other
applications which send, read, or otherwise process email. A quick
trip to the referenced page leaves no doubt that this means more than
replacing a few lines of code in a PowerShell script.
Thanks #postanote for your suggestions, the fix eventually came down to this:
from user#place.com I had to drop the 'place.com' and just keep the alias
with -SmtpServer smtp.office365.com I had to drop 'office365.com' and replace with '[uni].edu'
I've been trying to write a powershell script that sends an automated email as part of it's process using the logged in user's credentials. There are two primary methods that I've found to do this: Send-MailMessage and using a Net.Mail.SmtpClient object.
I've been able to get it up and running using the Net.Mail.SmtpClient object without issue, however that API is marked obsolete and so I'd prefer to not use it if possible, however I haven't been able to get Send-MailMessage to work using default credentials.
Without UseDefaultCredentials both of the scripts below fail with the same general message.
$smtpServer = "server.com"
$smtpFrom = "user#server.com"
$smtpTo = "user#server.com"
$messageSubject = "THIS IS WHERE YOUR SUBJECT GOES"
$messageBody = "This is a test of automated email at $([datetime]::Now.ToString('dd.MM.yyyy - HH.MM.SS'))"
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.EnableSsl = $true
$smtp.Port = 587
#$smtp.UseDefaultCredentials = $true
$smtp.Send($smtpFrom,$smtpTo,$messagesubject,$messagebody)
and
$mailsplat = #{
SmtpServer = 'server.com'
From = 'user#server.com'
To = 'user#server.com'
Subject = 'THIS IS WHERE YOUR SUBJECT GOES'
Body = "This is a test of automated email at $([datetime]::Now.ToString('dd.MM.yyyy - HH.MM.SS'))"
Port = 587
UseSSL = $true
#UseDefaultCredentials = $true
}
Send-MailMessage #mailsplat
"The SMTP server requires a secure connection or the client was not authenticated. The server
response was: 5.7.1 Client was not authenticated"
Fixing the first script is easy. If I uncomment out the UseDefaultCredentials line it works perfectly as expected. There's no UseDefaultCredentials or similar parameter available to Send-MailMessage however. I'd prefer to use the Send-MailMessage as it's the recommended method and the other is marked as obsolete, but I can't actually find a way to make it work with my requirements (despite a plethora of posts saying Send-MailMessage will use default credentials if none are provided and the documentation indicating it should)
I'm trying to write down a powershell script that will automatically finds the mailbox server and connect to it (using the URI https://mailboxserver/powershell).
Problem is I haven't found a way to automatically detect a mailbox server for a given exchange organization. I found a way how to find the CAS server because someone posted how the outlook finds this manually.
I tried to query AD but I do not know which attribute is unique to exchange mailbox server.
I also tried DNS records but found none which helps.
Does anybody know about a unique value of mailbox server which could be queried from AD or GC? Or a DNS record or something else I have not thought of?
Exchange 2010
I could post forest and domain functional level if necessary but I am on the way.
Thanks in advance
Your AD user attributes have this information, albeit you have to parse the mailbox server name from them.
HomeMTA
msExchHomeServerName
So if you have access to the AD cmdlets you might be able to get your mailbox server this way.
$adUser = get-aduser someuser -Properties msExchHomeServerName
$mailboxServerName = ($aduser.msExchHomeServerName -split "cn=")[-1]
Those attributes help you find your current mailbox is hosted. The mailbox server in my case was the last "item" in msExchHomeServerName so I split the string on "cn=" and then the last element of that array would be my mailbox server name.
Then you can use that to connect to an Exchange session!
$Credentials = Get-Credential
$exchangePath = "http://$mailboxServerName/PowerShell/?SerializationLevel=Full"
$ExSession = New-PSSession –ConfigurationName Microsoft.Exchange –ConnectionUri $exchangePath -Credential $Credentials –Authentication Kerberos
Import-PSSession $ExSession
Does the code below get you what you need? It uses EWS - see my SO post for further details on EWS.
# load the assembly
[void][Reflection.Assembly]::LoadFile("D:\Temp\Microsoft.Exchange.WebServices.2.2\lib\40\Microsoft.Exchange.WebServices.dll")
# set ref to exchange - may need to change the version
$s = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2)
# replace with your email address
$email = "your.email#domain.com"
# grab your own credentials
$s.UseDefaultCredentials = $true
# discover the url from your email address
$s.AutodiscoverUrl($email)
$s.Url.AbsoluteUri
I have looked all over the web and cannot find exactly what I am looking for. I am trying to write a Powershell (V2) script that emails a file using our internal Exchange server, but doesn't require Outlook. I have a user account to use for this, but I don't have Outlook available for the server it runs on. Can someone either provide a script (Or even a method) that allows me to send an email with a specified attachment, using an Exchange mailbox?
Thanks!
You can use the Send-MailMessage cmdlet. Type this at your console for more help:
Get-Help Send-MailMessage -Full
Check the second code example at the examples section:
Get-Help Send-MailMessage -Examples
This should do the trick but is missing the attachment. That shouldn't be hard to add.
function submit_report_smtp{
param($report)
trap{return 1}
$smtp_client = New-Object system.Net.Mail.SmtpClient
$smtp_client.Host = $smtp_host
$credentials = New-Object system.Net.NetworkCredential
$credentials.UserName = $smtp_user
$credentials.Password = $smtp_pass
$smtp_client.Credentials = $credentials
$smtp_client.send($smtp_from, $smtp_to, $title,$report)
return 0
}