Skip to main content

Problem:

When you use the "System.Net.Mail" classes in .Net to send an email using smtp how can you specify the logon details to the server.

Resolution:

To do this you can use the "System.Net.NetworkCredential" .Net Class.

Some example COBOL that uses this is:-

      $set sourceformat"variable"

       program-id. Program1 as "SMTP.Program1".

       environment division.

       configuration section.

       repository.

            class cMailMessage      as "System.Net.Mail.MailMessage"

            class cMailAddress      as "System.Net.Mail.MailAddress"

            class cSMTPClient       as "System.Net.Mail.SmtpClient"

            class cAttachment       as "System.Net.Mail.Attachment"

            class cMediaTypeNamesApp   as "System.Net.Mime.MediaTypeNames Application"

            class cNetworkCredential as "System.Net.NetworkCredential"

            .          

       

       data division.

       working-storage section.

       01  ws-mailmessage           cMailMessage.

       01  ws-smtpclient            cSMTPClient.

       78  mailfrom                 value "someone@microfocus.net".

       78  mailto                   value "XXXdavid.sands@microfocus.com".

      *78  mailto                   value "someone@somewhere.com".

       78  SmtpServer               value "myserver.domain.nowhere".

       78  mailsubject              value "Auto Generated from COBOL on .Net".

       78  mailbody                 value "<b>This is Line 1</b>." & x"0d0a" &

                                          "This is Line 2.".

       78  filename                 value "c:\\test.dat".        

       01  attFile                  cAttachment.                                   

       

       procedure division.

       

           invoke cMailMessage::"New" returning ws-mailmessage.

           set ws-mailmessage::"From"       to cMailAddress::"New"(mailfrom)

           invoke ws-mailmessage::"To"::"Add"(cMailAddress::"New"(mailto))

           set ws-mailmessage::"Subject"    to mailsubject

           set ws-mailmessage::"Body"       to mailbody

           set ws-mailmessage::"IsBodyHtml" to true

           

           set attFile to cAttachment::"New"(filename,cMediaTypeNamesApp::"Octet")

       

           invoke ws-mailmessage::"Attachments"::"Add"(attFile)    

       

           set ws-smtpclient to cSMTPclient::"New"(SmtpServer)

           set ws-smtpclient::"Credentials" to cNetworkCredential::"New"("username","password")

       

           invoke ws-smtpclient::"Send"(ws-mailmessage)

       

           goback.

       end program Program1.

Old KB# 3933