Sending Authenticated E-mail using .NET

The following code shows how to send an e-mail using the .NET System.Mail namespace. The code is written for APLX (discontinued in 2016), but can also be used with Dyalog after some modifications.

The example shows how to contact an SMTP mail server which requires authentication - i.e. requires you to provide a user name and password when the SMTP connection is established. This is an increasingly common requirement designed to combat anonymous Spam e-mails.

Depending on the SMTP server you are using, you may need to make some small changes to the code:

 

SendMessage;to;from;message;smtpClient;credentials
⍝ Example of sending an E-Mail message using .NET
⍝ See
⍝     http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx
 
⍝ Create a test message
to←'fredsmith@supernet.com'
from←'bob3@yahoo.com'
message←'.net' ⎕NEW 'System.Net.Mail.MailMessage' from to
message.Subject←'Pricing and Availability'
message.Body←'Did you get the new price list?',⎕R,'Thanks. Bob'
 
⍝ Create an SMTP client
⍝ (You may need to change the port number)
smtpClient←'.net' ⎕NEW 'System.Net.Mail.SmtpClient'
smtpClient.Host←'smtp.supernet.com'
smtpClient.Port←25
 
⍝ Set login credentials used to authenticate us to the SMTP server
⍝ (If your SMTP server doesn't use authentication, omit this bit)
credentials←'.net' ⎕NEW 'System.Net.NetworkCredential'
credentials.UserName←'myusername'
credentials.Password←'mysecretpassword'

⍝ Note: The order of these two lines seems to matter
⍝ If they are reversed, may get a .NET exception:
⍝     System.Net.Mail.SmtpException: The SMTP server requires 
⍝     a secure connection or the client was not authenticated. 
⍝     The server response was: 5.5.1 Authentication Required

smtpClient.UseDefaultCredentials←0
smtpClient.Credentials←credentials
 
⍝ Use SSL for secure connection
⍝ (If your SMTP server doesn't use SSL, omit this bit)
smtpClient.EnableSsl←1
 
⍝ Send the message
smtpClient.Send message

Author: SimonMarsden

CategoryDotNet CategoryEmail

AuthenticatedEmail (last edited 2017-02-16 19:40:56 by KaiJaeger)