-2

I've got this code that sends an email with attachment[s]:

internal static bool EmailGeneratedReport(List<string> recipients)
{
    bool success = true;
    try
    {
        Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application();
        MailItem mailItem = app.CreateItem(OlItemType.olMailItem);
        Recipients _recipients = mailItem.Recipients;
        foreach (string recip in recipients)
        {
            Recipient outlookRecipient = _recipients.Add(recip);
            outlookRecipient.Type = (int)OlMailRecipientType.olTo;
            outlookRecipient.Resolve();
        }
        mailItem.Subject = String.Format("Platypus Reports generated {0}", GetYYYYMMDDHHMM());
        List<String> htmlBody = new List<string>
        {
            "<html><body><img src=\"http://www.platypus.com/wp-content/themes/duckbill/images/pa_logo_notag.png\" alt=\"Pro*Act logo\" ><p>Your Platypus reports are attached.</p>"
        };
        htmlBody.Add("</body></html>");
        mailItem.HTMLBody = string.Join(Environment.NewLine, htmlBody.ToArray());

        . . . // un-Outlook-specific code elided for brevity

        FileInfo[] rptsToEmail = GetLastReportsGenerated(uniqueFolder);
        foreach (var file in rptsToEmail)
        {
            String fullFilename = Path.Combine(uniqueFolder, file.Name);
            if (!File.Exists(fullFilename)) continue;
            if (!file.Name.Contains(PROCESSED_FILE_APPENDAGE))
            {
                mailItem.Attachments.Add(fullFilename);
            }
            MarkFileAsSent(fullFilename);
        }
        mailItem.Importance = OlImportance.olImportanceHigh;
        mailItem.Display(false);
    }
    catch (System.Exception ex)
    {
        String exDetail = String.Format(ExceptionFormatString, ex.Message,
            Environment.NewLine, ex.Source, ex.StackTrace, ex.InnerException);
        MessageBox.Show(exDetail);
        success = false;
    }
    return success;
}

However, it pops up the email window when ready, which the user must respond to by either sending or canceling. As this is in an app that sends email based on a timer generating reports to be sent, I can't rely on a human being present to hit the "Send" button.

Can Outlook email be sent "silently"? If so, how?

I can send email silently with gmail:

private void EmailMessage(string msg)
{
    string FROM_EMAIL = "sharedhearts@gmail.com";
    string TO_EMAIL = "cshannon@platypus.com";
    string FROM_EMAIL_NAME = "B. Clay Shannon";
    string TO_EMAIL_NAME = "Clay Shannon";
    string GMAIL_PASSWORD = "theRainNSpainFallsMainlyOnDonQuixotesHelmet";

    var fromAddress = new MailAddress(FROM_EMAIL, FROM_EMAIL_NAME);
    var toAddress = new MailAddress(TO_EMAIL, TO_EMAIL_NAME);
    string fromPassword = GMAIL_PASSWORD;
    string subject = string.Format("Log msg from ReportScheduler app sent 
{0}", DateTime.Now.ToLongDateString());
    string body = msg;

    var smtp = new SmtpClient
    {
        Host = "smtp.gmail.com",
        Port = 587,
        EnableSsl = true,
        DeliveryMethod = SmtpDeliveryMethod.Network,
        UseDefaultCredentials = false,
        Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
    };
    using (var message = new MailMessage(fromAddress, toAddress)
    {
        Subject = subject,
        Body = body
    })
    {
        smtp.Send(message);
    }
}

...but when I do that, I have to supply my gmail password, and I don't really want to do that (expose my password in the source code).

So, how can I gain the benefits of gmailing (silence) and Outlook (keeping my password private)?

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862

2 Answers2

4

If you want the shortest way:

System.Web.Mail.SmtpMail.SmtpServer="SMTP Host Address";
System.Web.Mail.SmtpMail.Send("from","To","Subject","MessageText");
JWP
  • 6,672
  • 3
  • 50
  • 74
  • How that code will work with MailItem in outlook. Is SMTP server need credentials. So you will not be able the send by the smtp server object if you don't provide the credentials. So how your code would work ? – Cédric Boivin Jun 02 '17 at 14:51
  • It depends on the configuration of Outlook, by default it uses IMAP protocol and not SMTP. However, if it has support for SMTP, then yes you have to send in credentials prior to getting to the point above. – JWP Jun 02 '17 at 15:40
0

This was code that I was reusing from another project where I wanted the send dialog to display, and for the email only to be sent when the user hit the "Send" button. For that reason, it didn't call "send"

To get the email to send silently/unattended, I just needed to add a call to "mailItem.Send()" like so:

mailItem.Importance = OlImportance.olImportanceHigh;
mailItem.Display(false);
mailItem.Send(); // This was missing
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862