powershell email smtp with startls - powershell

Need to send email via private smtp server with credential and starttls. I read many tutorials and still cannot establish starttls communication.
My code:
$smtpServer = "smtp.xserver.cz"
#Creating a Mail object
$msg = new-object Net.Mail.MailMessage
#Creating SMTP server object
$smtp = new-object Net.Mail.SmtpClient($smtpServer, 25)#587 works
$smtp.EnableSsl = $false
$smtp.Credentials = New-Object System.Net.NetworkCredential("myuser#xserver.cz","mypassword"); #yes, correct login, tried via Thunderbird
#Email structure
$msg.From = "info#xserver.cz"
$msg.To.Add("testtest#gmail.com")
$msg.subject = "subject"
$msg.IsBodyHTML = $true
$msg.body = "AAA"+"<br /><br />"
$ok=$true
try{
$smtp.Send($msg)
Write-Host "SENT"
}
catch {
Write-Host "`tNOT WORK !!!!!"
$error[0]
$_.Exception.Response
$ok=$false
}
finally{
$msg.Dispose()
}
if($ok){
Write-Host "`tEVERYTHING OK"
}
Need to use .Net objects and class, not third party library, or Send-MailMessage in Powershell, because Send-MailMessage doesn't have atachment sending options.

You're not getting your TLS connect because you've set EnableSsl to $false.
Not sure where you got the idea that Send-MailMessage doesn't have attachment sending options. Sending attachments with Send-MailMailMessage is ridiculously easy. It accepts one or more file names to use as attachments from the pipeline, or through the -Attachments parameter.

Related

How to fix 'the SMTP server requires a secure connection or the client was not authenticated' error when the server response was 5.7.0?

I did turn on my less secure app in Gmail, I think the problem is SSL.
$time = get-date
$smtpServer = “smtp.gmail.com”
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential(“user”, “password”)
$smtp = new-object Net.Mail.SmtpClient($smtpServer,587) **587 to 465**
$msg = new-object Net.Mail.MailMessage
$msg.From = (“myemail#gmail.com”)
$msg.To.Add(“myemail#gmail.com”)
$body=”Your message Body”
$msg.Subject = “Mail From Gmail ” + $time
#your file location
$files=Get-ChildItem “C:\Users\Public\Pictures\LINE”
Foreach($file in $files)
{
Write-Host “Attaching File :- ” $file
$attachment = New-Object System.Net.Mail.Attachment –ArgumentList
C:\Users\Public\Pictures\LINE\$file
$msg.Attachments.Add($attachment)
}
$smtp.Send($msg)
$attachment.Dispose()
$msg.Dispose()
Have you tried to change the port?
It looks to me that you're still using 587 which is expecting TLS/SSL or STARTTLS.
Is there a reason you're not authenticating and using SSL/TLS ?
I've read that Google does not fall back to plaintext SMTP if STARTTLS is not supported. If you've explicitly selected the "Unsecured" option when configuring the server I believe you need to use a different port. 25(maybe).
Edit: It looks like you're missing arguments on the send method. Try this code.
Alternatively try changing for the much easier looking Send-MailMessage cmdlet
https://learn.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Send-MailMessage?view=powershell-5.1
$EmailFrom = "notifications#somedomain.com"
$EmailTo = "me#earth.com"
$Subject = "Notification from XYZ"
$Body = "this is a notification from XYZ Notifications.."
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("username", "password");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
I had a similar problem at one point with a script of mine. On mobile right now, but if I remember right, I ended up making an app password for the use and turned off the Less secure app option.
https://support.google.com/accounts/answer/185833?hl=en

Email multiple people individual attachments

I am using Send-MailMessage to email multiple different recipients each with an individual report. I have just been repeating the Send-Mail command with the different attachment paths for each recipient however the problem I am running into since I also have to use -UseSsl -credential I have to authenticate each time a new message is sent. Is there a way to authenticate once without having to do it each time?
Send-MailMessage is a wrapper for .net smtpclient. You can do your custom version of it, for example:
$client = New-Object System.Net.Mail.SmtpClient
$client.EnableSsl = $true
$client.Host = "smtp.server.com"
$client.Credentials = $creds
foreach ($r in $recipients) {
$from = "from#mail.com"
$to = $r
$msg = New-Object System.Net.Mail.MailMessage $from, $to
$msg.Subject = "subject"
$msg.Body = "body"
$msg.Attachments.Add("C:\temp\test.html")
$client.Send($msg)
}

Send email via SMTP Mail server

I have installed SMTP Virtual Server in windows server 2012 r2. Later I have used following PowerShell script to send the email. Which was successful
$email = "xxxxxxxxxx#xxxxxx.com"
$pass = "xxxxxxx"
$smtpServer = "smtp.office365.com"
$smtpPort = "25"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.EnableSsl = $true
$msg.From = "$email"
$attachment = New-Object Net.Mail.Attachment("C:abcd/123.txt");
$msg.Attachments.Add($attachment);
$msg.To.Add("xxxx#xxxxx.com")
$msg.BodyEncoding = [system.Text.Encoding]::Unicode
$msg.SubjectEncoding = [system.Text.Encoding]::Unicode
$msg.IsBodyHTML = $true
$msg.Subject ="List of users"
$msg.Body=$msg.Body = "<h2> hi everyone </h2>
$SMTP.Credentials = New-Object System.Net.NetworkCredential("$email", "$pass");
$smtp.Send($msg)
here my question is can I send email without using from address in the above script(Is there any chance to save from email address and credentials somewhere in SMTP virtual server settings so that script can take credentials directly). I don't want to use from email address and credentials in above script
I'd suggest using Send-MailMessage instead of manual .NET manipulation:
$Creds = Import-CliXml -Path 'C:\mycreds.xml'
$MailArgs = #{ 'SmtpServer' = 'smtp.office365.com'
'Port' = 25
'To' = 'xxxx#xxxxx.com'
'From' = $Creds.UserName
'Subject' = 'List of users'
'Attachments' = 'C:\abcd\123.txt'
'Body' = '<h2> hi everyone </h2>'
'Encoding' = [Text.Encoding]::Unicode
'BodyAsHtml' = $true
'UseSsl' = $true
'Credential' = $Creds
}
Send-MailMessage #MailArgs
And you would create your $Creds object as follows:
Get-Credential -Credential 'xxxxxxxxxx#xxxxxx.com' | Export-CliXml -Path 'C:\mycreds.xml'
There are a couple extra options you might be interested in (such as notification of delivery) you can read about in the doc linked above.
Additionally, your password is encrypted when exported using Export-CliXml specific to that device and account utilizing DPAPI.

Send mail via powershell without authentication

I was using nant to send mail and it is working fine - something like
<mail
from="Test#b.c"
tolist="A#b.c"
subject="Test"
mailhost="myhost.mydomain.com"
isbodyhtml="true"
message= "${Test}">
</mail>
I didn't have to use any kind of authentication.
Now when using powershell it seems I am forced to use authentication - something like this would fail:
Send-MailMessage -To $to -From $from -Subject "Test" –Body “Test (body) -SmtpServer "myhost.mydomain.com"
I would get the following message:
Send-MailMessage : No credentials are available in the security package
Am I missing some way to send mails without specifying credentials if the server supports that?
Edit:
I've also tried the answer here to send anonymous mails but it just times out:
send anonymous mails using powershell
Sending mails using Powershell v1 method works fine without authentication as shown here
My Powershell version is 5 yet this is apparently the way to go, unless someone has another idea.
$smtpServer = "ho-ex2010-caht1.exchangeserverpro.net"
$smtpFrom = "reports#exchangeserverpro.net"
$smtpTo = $to
$messageSubject = $subject
$messageBody = $body
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($smtpFrom,$smtpTo,$messagesubject,$messagebody)
I was looking for another issue and found this question here...
As #AngelicCore already explained one approach,
Here is another one if someone using Outlook dektop app...
The mail sent will appear in your outbox.
using outlook object
Try
{
#Email structure
$Outlook = New-Object -ComObject Outlook.Application
$Mail = $Outlook.CreateItem(0)
#Email Recipients
$Mail.To = "abc#domain.com;xyz#domain.com"
$Mail.Cc = "tuv#domain.com; pqr#domain.com"
#Email Subject
$date = Get-Date -Format g
$Mail.Subject = "Subject here $date"
#Email Body
$Mail.Body = "Body Here"
#Html Body
$Mail.HTMLBody == "<html> HTML Body Here </html>"
#Email Attachment
$file = "C:\path\xyz.txt"
$Mail.Attachments.Add($file)
$Mail.Send()
Write-Host -foreground green "Mail Sent Successfully"
}
Catch
{
write-host -foreground red $error[0].Exception.Message
}
pause
exit

Send mail trough TELNET over OVH with .batch script

I would like to use TELNET to send an email with the content of log.txt using one of my OVH mail accounts (noreply#clement.business hosted on OVH) to a gmail address. Due to my society security politics I am not able to install anything on the servers but the OS itself.
So I tried with both batch and PowerShell but without success, I even tried manually, I can telnet OVH but then don't know how to login.
Here's a few things I tried :
$subject = $args[0]
# Create from/to addresses
$from = New-Object system.net.mail.MailAddress "noreply#clement.business"
$to = New-Object system.net.mail.MailAddress "random#gmail.com"
# Create Message
$message = new-object system.net.mail.MailMessage $from, $to
$message.Subject = $subject
$message.Body = #"
Am I even suppose to write here
"#
# Set SMTP Server and create SMTP Client
$server = "I have no idea how to OVH here"
$client = new-object system.net.mail.smtpclient $server... Server what, POP3 ?
# Do
"Sending an e-mail message to {0} by using SMTP host {1} port {2}." -f $to.ToString(), $client.Host, $client.Port
try {
$client.Send($message)
}
catch {
"Exception caught in CreateTestMessage: {0}" -f $Error.ToString()
}
I cannot figure that out, it is such a struggle to deal with...
PS : I did use the OVH guide about POP3/SMTP setup, but did not work, or I have no idea what I am doing. Useful link here as well.
Just so you know the difference: POP3 is used to receive email, SMTP is used to send email. You can't use them interchangeably.
A quick google for 'ovh smtp server' shows that the ovh help pages list the SMTP servers as:
Server name: ns0.ovh.net
Port of the outgoing server: 587
Username: identical to the email address
Password: your password for your account, as defined in the creation of the email address
I can't test these as I don't have an ovh account.
I would use Send-MailMessage to send the email as it's much easier to use than your solution:'
This will send an email with the file log.txt as an attachment:
$username = "noreply#clement.business"
$password = "passwordforemailaddress" | ConvertTo-SecureString
$credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password
$parms = #{
From = "noreply#clement.business"
To = "email#gmail.com"
Attachment = "C:\folder\log.txt"
Subject = "Daily Logs"
Body = "Your body text here"
SMTPServer = "ns0.ovh.net"
SMTPPort = "587"
Credential = $credentials
}
Send-MailMessage #params
And these params this will use log.txt as the email body text:
$parms = #{
From = "noreply#clement.business"
To = "email#gmail.com"
Body = Get-Content "C:\folder\log.txt"
Subject = "Daily Logs"
SMTPServer = "ns0.ovh.net"
SMTPPort = "587"
Credential = $credentials
}