I have a WPF C # project where I have a function to send emails, with Microsoft.Office.Interop.Outlook._MailItem but I don't know how to configure the sender account, it is a gmail account, and I don't know how to tell it or how to give it the username and password of it, can someone guide me?
public void sendEMailThroughOUTLOOK(string PDFAdjunto, string XMLAdjunto, string from, string[] to, string subject, string body, string cc)
{
try
{
Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
// Create a new mail item.
Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
// add to's
if (to[0] != string.Empty && to[0] != null)
{
oMsg.Recipients.Add(to[0]);
}
if (to[1] != string.Empty && to[1] != null)
{
oMsg.Recipients.Add(to[1]);
}
// Mail body
oMsg.Body = body;
oMsg.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatPlain;
// Mail attachments
Microsoft.Office.Interop.Outlook.Attachment oAttach1 = oMsg.Attachments.Add(XMLAdjunto);
Microsoft.Office.Interop.Outlook.Attachment oAttach2 = oMsg.Attachments.Add(PDFAdjunto);
// Mail subject
oMsg.Subject = subject;
// Resolve accounts
oMsg.Recipients.ResolveAll();
// Send mail
((Microsoft.Office.Interop.Outlook._MailItem)oMsg).Send();
// Clean up.
oMsg = null;
oApp = null;
}
catch (System.Exception e)
{
Mensaje = new wMensaje("Error en envío de Mail", DateTime.Now.ToString()
+ System.Environment.NewLine + subject
+ System.Environment.NewLine + " De: '" + from + "' "
+ System.Environment.NewLine + " Para: '" + to[0] + "', '" + to[1] + "' '"
+ (e.Message.Contains("Operación anulada") ? System.Environment.NewLine + System.Environment.NewLine + "--> Asegúrese de tener ABIERTO su Outlook <--" : "")
+ System.Environment.NewLine + System.Environment.NewLine + " Error: "
+ System.Environment.NewLine + System.Environment.NewLine
+ (e.InnerException == null ? e.Message : e.InnerException.ToString()));
Mensaje.ShowDialog();
}
}
I don't know how to configure the sender account, it is a gmail account, and I don't know how to tell it or how to give it the username and password of it
You can use the MailItem.SendUsingAccount property which returns or sets an Account
object that represents the account under which the MailItem
is to be sent. The SendUsingAccount
property can be used to specify the account that should be used to send the MailItem
when the Send
method is called. This property returns Null
(Nothing
in Visual Basic) if the account specified for the MailItem
no longer exists.
Note, to be able to set up the SendUsingAccount
property it must be configured in the Outlook profile.
You may also consider using the System.Net.Mail
namespace, read more about that in the Send email using System.Net.Mail through gmail article.