I cant get this to work on a windows 7 client with powershell 2
$smtpServer = "smtp.example.com"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = "fromID#example.com"
$msg.ReplyTo = "replyto#example.com"
$msg.To.Add("toID#example.com")
$msg.subject = "My Subject"
$msg.body = "This is the email Body."
$smtp.Send($msg)
I am getting an exception that says "Exception calling "Send with "1" arguments" Failure Sending mail"
Anyone have any idea?
I have tried Send-MailMessage but it also fails, if I run the command on a server based windows it executes fine.
I use the same account for the procedures.
This could be due to many reasons, but one issue that I had seen this exact same error was because an anti-virus program was blocking Powershell from sending the email. Check if this is the case by looking at your anti virus logs.
Beyond that, you might want to check if firewall is fine, you can connect to the SMTP server etc.
This might work:
$ol = New-Object -comObject Outlook.Application
$mail = $ol.CreateItem(0)
$Mail.Recipients.Add("XXX#YYY.ZZZ")
$Mail.Subject = "PS1 Script TestMail"
$Mail.Body = "Test Mail"
$Mail.Send()
# you can use this for HTML-Mails
# $Mail.HTMLBody = "<HTML><HEAD>Text<B>BOLD</B> <span style='color:#E36C0A'>Color Text</span></HEAD></HTML>"
# you can use this for attache a file
# $Mail.Attachments.Add("D:\scripte\ol.txt")
For further reference.
Changing port to 25 works, but why ?
Related
I am using a FileZilla Server as an FTP. I want to create a PowerShell script that will send an email as soon as a file is uploaded.
I have been using the knowledge in this article: https://richjenks.com/filezilla-email-notifications/
and below is the code of my fn.ps1 file
$EmailFrom = "SENDER_EMAIL"
$EmailTo = "RECIPIENT_EMAIL"
$Subject = "New File Uploaded to FileZilla"
$Body = "A new file has been uploaded to the FTP server on FileZilla"
$SMTPServer = "127.0.0.1"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 21)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object
System.Net.NetworkCredential("GMAIL_ADDRESS", "GMAIL_PASSWORD");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
The only problem is that no email is actually sent? I can see the PowerShell pop up briefly after a file is uploaded so it is being run upon file upload, however no email is actually sent anywhere.
Any help would be greatly appreciated.
EDIT: I am not entirely sure what is the relationship between "SENDER_EMAIL" and "GMAIL_ADDRESS", I found the above solution on another website and they are different, should these not be the same?
Make sure you understand that the script actually has nothing to do with your FTP server. It is just a plain PowerShell script that sends a fixed email. So everything in the script is related to your SMTP mail server, not to your FTP server. So...
What goes to SmtpClient constructor is the address of your SMTP mail server. You seem to be using an address of your FTP server.
$SMTPServer = "127.0.0.1"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 21)
Check the example you have based this on. They use smtp.gmail.com:587.
Similarly, what goes to SmtpClient.Credentials are credentials to your SMTP mail server. So some real values, not placeholders like these:
$SMTPClient.Credentials = New-Object
System.Net.NetworkCredential("GMAIL_ADDRESS", "GMAIL_PASSWORD");
For Gmail they would be your Gmail address and password.
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 have created a small PS script to create an email for my pipeline to send out whenever there is a deployment. the problem is i dont want the email to be sent from my personal email but from the company outlook email. i searched and saw different SMTP server names and using mail.from but i cant get it to work. can someone help me out?
param(
[Parameter(Mandatory=$true,Position=0)]
[string]$Address1,
[Parameter(Mandatory=$true,Position=1)]
[string]$Address2,
[switch]$Recurse,
[switch]$Force
)
$ol = New-Object -comObject Outlook.Application
$mail = $ol.CreateItem(0)
$Mail.Recipients.Add($Address1)
$Mail.Recipients.Add($Address2)
$Mail.Subject = "DSC Deployment in Progress"
$Mail.Body = "There is a DSC install beginning. . ."
$Mail.Send()
You need to assign a value to the SendUsingAccount property. The account can be found in the (outlook).Session.Accounts collection.
$sendSmtpAddress = "some.name#somedomain.com"
$account = $ol.session.acounts | ? { $_.smtpAddress -eq $sendSmtpAddress }
then, assign to the SendUsingAccount property before sending
$mail.SendUsingAccount = $account
$mail.Send()
Full example
$sendSmtpAddress = "some.name#somedomain.com"
$ol = new-object -comobject "outlook.application"
$account = $ol.session.accounts | ? { $_.smtpAddress -eq $sendSmtpAddress }
$mail = $ol.CreateItem(0)
$mail.recipients.add("target.user#somedomain.com") | out-null
$mail.subject = "test email"
$mail.body = "test email"
$mail.SendUsingAccount = $account
$mail.Send()
For what it's worth, I gave up trying to send email via Outlook a long time ago, it's much easier to use plain SMTP. Depending on the security policy on your local SMTP server (Exchange?), you may be able to 'send as' any user on your local domain. Ask your IT people for the name/IP of an internal SMTP server that you can use to send email, and then it's as easy as:
send-mailmessage -smtpServer (servername or IP) -from sender.name#domain.com -to #(recipient1#domain.com, recipient2#domain.com) -subject "Email Subject" -body "Email Body"
If using send-mailmessage, it's possible to set a Display Name for the sender by using the form "Display Name <sender.name#domain.com>" e.g.
-from "Deployment Alerts <sender.name#domain.com>"
Recipients will see the Display Name in their email client, rather than the SMTP address.
A couple of points that I consider to be good practice:
Depending on the config of the SMTP server, there may be little, or no verification of the 'sender' address. It is worth using a genuine account that you have access to, so that you have sight of any bounce / non-delivery reports.
Consider including something in the mail body (perhaps a footer) that mentions where the alert came from and what process generated it. This can help your successor or colleague track down the script in the future.
The assignment like
$mail.SendUsingAccount = $account
worked for me since Windows Server 2000 till Windows Server 2008 and from Outlook 2007 till Outlook 2016. Since Windows Server 2016 I've got an exception (The server threw an exception. (Exception from HRESULT: 0x80010105 (RPC_E_SERVERFAULT))).
But there is an alternative way to assign this property.
[Void] $mail.GetType().InvokeMember("SendUsingAccount","SetProperty",$NULL,$mail,$account)
Can anyone help me out, we need to send mail through command line from Window server. We cannot use Blat as per security issue and neither do we want to install Exchange resource kit. We have our own Mail exchange server we can make use of it.
May be if any batch which could be run to access our SMTP mail server.
Thanks in advance.
Assuming you don't want to install any SMTP client whatsoever, and just want to use windows and perhaps batch files, you could use Telnet to connect to port 25 of your smtp server and send the commands manually.
Here is an example of how to do this.
Anyway, I personally would prefer to install some command line SMTP client such as Blat or Bmail, instead of going into the hassle of directly interacting with SMTP.
I got this resolved without using any SMTP clients. I used Windows Powershell script to send mail and it is working very well.
Please check the below link
http://blogs.msdn.com/b/powershell/archive/2009/10/30/sending-automated-emails-with-send-mailmessage-convertto-html-and-the-powershellpack-s-taskscheduler-module.aspx
Happy coding !!
a very nice solution I found generically good if no authentication is involved and no programs can/should be installed or can be assumed to exist is the following, which should work on Ubuntu and other Linux platforms alike (you can put everything in one line using the ; command delimiter and removing the \ chars in the echo quoted string):
set sender="<sender#example.com>"
set recipient="<recipient#example.com>"
set subj="testsubj"
set body="testbody"
set srv="mysmtpsrv.com"
set port="25"
set crlf="\x0D\x0A"
echo "EHLO man${crlf}\
MAIL FROM: ${sender}${crlf}\
RCPT TO: ${recipient}${crlf}\
data${crlf}\
Subject: ${subj}${crlf}${crlf}\
${body}\
${crlf}.${crlf}"\
|\
nc -Ci 1 ${srv} ${port}
(Using like this make sure you are saving the file in Unix style (only a \x0A character will be added after the echo "...\ backslashes).
Otherwise just remove the backslashes and the newline which puts everything on a line and makes it work, but less visually structured.)
HowToGeek demonstrates a Windows PowerShell script that works very well at How To Send Email From the Command Line in Windows Without Extra Software
Here is the method:
First you're defining the variables:
$EmailFrom = “yourMail#gmail.com”
$EmailTo = “theRecipient'sAddress#someServer.com”
$Subject = “your subject”
$Body = “some text”
$SMTPServer = “smtp.gmail.com”
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential(“yourGmailUsername”, “password”);
Then, you're using this command to send the mail:
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
You'll need a valid Gmail account in order to authenticate as a Gmail user.
To send mail from command line in windows:-
Save this in a text file and name that file something like sendmail.ps1
$EmailFrom = "from#gmail.com"
$EmailTo = "to#domain.com"
$Subject = "The subject of your email"
$Body = "What do you want your email to say"
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("gmail_username", "password");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
-Don't forget to put the valid email address and password.
Now open CMD and write this command
Powershell -ExecutionPolicy ByPass -File C:\sendmail.ps1
Voila! mail sent!!
This is an example to send mail from your Gmail address, for other servers you need to change the -smtp and -port
$securepass = ConvertTo-SecureString -String $yourpassword -A -F
$credential=new-object PSCredential $yourusername,$securepass
send-mailmessage -from "$yourusername#gmail.com" -to $recipient -subject "subject" -body "message" -smtpserver smtp.gmail.com -port 587 -usessl -credential $credential -encoding utf8
Here is the script that can send mail from your Gmail:
https://gallery.technet.microsoft.com/scriptcenter/PC-Utilities-Downloader-355e5bfe
I have a .msg file on my filesystem. With powershell I can open a Outlook window with the message simply like this:
Invoke-Item "MY MAIL.msg"
How to change the subject and forward it to a given address via Powershell?
Thanks in advance
We had a problem that required the email to be forwarded from Outlook, there was 3000~ emails to do.
The answer Iain had given led me down the path to success, so thank you.
However it did not work for me as given, it failed. I noticed that you need to save the method of the forward to a variable and then execute the code from that, below is my complete script for looping through each msg file in a folder and forwarding it to a person.
I also left the subject as it was and gave no body as this was not needed.
#Open Outlook and get a list of emails to forward
$Outlook = New-Object -comObject Outlook.Application
$Emails = Get-ChildItem -Path C:\Users\APerson\Documents -Filter *.msg
#Loop through each email and open it up
Foreach($Email IN $Emails){
$Message = $Outlook.Session.OpenSharedItem($($Email.FullName))
$Forward = $Message.Forward()
$Forward.Recipients.Add('a.person#gmail.com')
$Forward.Send()
#Sleep is optional :D
Start-Sleep -Seconds 1
}
#Close Outlook
$Outlook.Quit()
Also noticed if you have a security policy applied to Outlook that is stopping you from running this script, for example it will remove the Add() on recipients, just import these registry settings (can be saved as a reg file):
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Policies\Microsoft\office\14.0\outlook\security]
"PromptOOMSend"=dword:00000002
"PromptOOMAddressBookAccess"=dword:00000002
"PromptOOMAddressInformationAccess"=dword:00000002
"PromptOOMMeetingTaskRequestResponse"=dword:00000002
"PromptOOMSaveAs"=dword:00000002
"PromptOOMFormulaAccess"=dword:00000002
"PromptSimpleMAPISend"=dword:00000002
"PromptSimpleMAPINameResolve"=dword:00000002
"PromptSimpleMAPIOpenMessage"=dword:00000002
You could try something like this, works with outlook 2010
$ol = New-Object -comObject Outlook.Application
gm -InputObject $ol
$mail = $ol.Session.OpenSharedItem("C:\Users\fred\Desktop\Test Email Subject.msg")
$mail.Forward()
$Mail.Recipients.Add("fred#bloggs.com")
$Mail.Subject = "Test Mail"
$Mail.Body = " Test Mail 22222 "
$Mail.Send()
In PowerShell 2.0 there is a Send-MailMessage cmdlet that allows you to attach files, specify a subject and a recipient e.g.:
Send-MailMessage -smtpServer smtp.doe.com -from 'joe#doe.com' `
-to 'jane#doe.com' -subject 'Testing' -attachment foo.txt
Not sure how that plays with .msg files but you might give it a try.