i already have a mail service, but i need to use different from address, because this service is used by many services. Now, i have this code, which works fine:
public static bool SendMail(Mail mail)
{
var smtp = new SmtpClient();
var credential = (NetworkCredential) smtp.Credentials;
var mailMessage = new MailMessage
{
From = new MailAddress(credential.UserName, mail.DisplayName),
Subject = mail.Subject,
Body = mail.Body,
IsBodyHtml = true
};
mailMessage.To.Add(new MailAddress(mail.To));
if (!string.IsNullOrEmpty(mail.TemplatePath))
mailMessage = embedImages(mailMessage, mail);
smtp.Send(mailMessage);
return true;
}
> And the web.config:
<mailSettings>
<smtp from="mail@gmail.com">
<network host="smtp.gmail.com" enableSsl="true" port="587" userName="mail@gmail.com" password="123456" />
</smtp>
</mailSettings>
> The Mail parameter, is an object:
public class Mail
{
public string Subject { get; set; }
public string Body { get; set; }
public string To { get; set; }
public string TemplatePath { get; set; }
public string DisplayName { get; set; }
public string From { get; set; }
}
So, by default, it should use the mailSettings, but, if the property mail.From != null, it should be sent by that mail.
Thanks
Are you trying to send to a message from multiple from addresses or do you want to be able to use this same method with different from addresses?
If you want to be able to reuse this method with different from addresses at different points of time, you could pass in the credentials in the method as a parameter. Then you will be able to set up smtp based off the credentials supplied from the parameter.
I don't see any place you are reading the mailSettings you set up. So I don't see how youre configuring your smtp.
Here's how I send alert emails using SmtpClient. I'm using ConfigurationManager.AppSettings, but the same idea applies for whatever type of config file you are using: attempt to get the "from" email, and if it is null use a default value.
string subject = "Email subject here."
string msg = "Email body here."
string fromEmail = ConfigurationManager.AppSettings["fromEmail"];
if (fromEmail == null)
fromEmail = "default.address@gmail.com"
string emailServer = ConfigurationManager.AppSettings["emailServer"];
int emailServerPort = int.Parse(ConfigurationManager.AppSettings["emailServerPort"]);
string toEmail; //email recipients
SmtpClient client = new SmtpClient(emailServer, emailServerPort);
MailMessage mail = new MailMessage(fromEmail, toEmail, subject, msg);
client.Send(mail);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.