Ive gone through many posts, but none seem to work.
I have an MVC application hosted in Azure as an app service and sending of mails is not working. It works on my local.
I have my SMTP details stored in my Web.Config:
Web.Config
<appSettings>
<!--To Send Mail-->
<add key="MailServerSMTP" value="mail.appname.com" />
<add key="MailServerSMTP_UserName" value="alerts#appname.com" />
<add key="MailServerSMTP_Password" value="Password" />
</appSettings>
Below is my sending function:
Email sending function
public void SendMessage(string subject, string messageBody, string fromAddress, string toAddress, string ccAddress, string sFileName, string sFileName2)
{
try
{
MailMessage message = new MailMessage();
SmtpClient client = new SmtpClient();
//Thread T1 = new Thread(delegate ()
//{
//Set the sender's address
message.From = new MailAddress(fromAddress);
//Allow multiple "To" addresses to be separated by a semi-colon
if ((toAddress.Trim().Length > 0))
{
foreach (string addr in toAddress.Split(';'))
{
message.To.Add(new MailAddress(addr));
}
}
//Allow multiple "Cc" addresses to be separated by a semi-colon
if ((ccAddress.Trim().Length > 0))
{
foreach (string addr in ccAddress.Split(';'))
{
message.CC.Add(new MailAddress(addr));
}
}
//Set the subject and message body text
if (!string.IsNullOrEmpty(sFileName))
{
Attachment obAttachement = new Attachment(sFileName);
message.Attachments.Add(obAttachement);
}
if (!string.IsNullOrEmpty(sFileName2))
{
Attachment obAttachement = new Attachment(sFileName2);
message.Attachments.Add(obAttachement);
}
message.Subject = subject;
message.Body = messageBody;
message.IsBodyHtml = true;
string path = System.AppDomain.CurrentDomain.BaseDirectory;
path = path.Replace("bin\\Debug\\", "Content\\img");
//if (path.Substring(path.Length - 6) != "Images")
//{
// path = path + "Images";
//}
if (path.GetLast(6) != "Content\\img")
{
path = path + "Content\\img";
}
Attachment ImageAttachment = new Attachment(path + "\\SystemicLogic_Transparent.png");
// Set the ContentId of the attachment, used in body HTML
ImageAttachment.ContentId = "SystemicLogic_Transparent.png";
// Add an image as file attachment
message.Attachments.Add(ImageAttachment);
message.Body = messageBody;
//Set the SMTP server to be used to send the message
//client.Host = "smtp.jumpstartcom.co.za"
string sSMTP_Username = ConfigurationManager.AppSettings["MailServerSMTP_UserName"].ToString();
string sSMTP_Password = ConfigurationManager.AppSettings["MailServerSMTP_Password"].ToString();
string appname = ConfigurationManager.AppSettings["MailServerSMTP"];
client.Credentials = new System.Net.NetworkCredential(sSMTP_Username, sSMTP_Password);
client.Host = appname;
client.Port = 587;
//client.EnableSsl = true;
//Send the e-mail message
//client.SendAsync(message, null);
client.Send(message);
//});
//T1.Start();
}
catch (Exception ex)
{
}
}
I have tried enabling SSL and using port 25. I have tried setting the port to 465 and 587 and emails are not coming through though.
Is there a specific port that needs to be used, or something I am doing wrong ?
Thanks for any help in advance!
Related
We have a program that sends an email for approval and extracting the reply using SSE.
In local computer the program is working, no error encountered. However when the program is published in our server we're experiencing some SockectException with the native error code 10060
Error Message
We're using SSE to check all the inbox using this code
public class MailRepository
{
private readonly string mailServer, login, password;
private readonly int port;
private readonly bool ssl;
public MailRepository(string mailServer, int port, bool ssl, string login, string password)
{
this.mailServer = mailServer;
this.port = port;
this.ssl = ssl;
this.login = login;
this.password = password;
}
public IEnumerable<IMessage> GetAllMails()
{
var messages = new List<IMessage>();
using (var client = new ImapClient())
{
client.Connect(mailServer, port, ssl);
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
client.Authenticate(login, password);
// The Inbox folder is always available on all IMAP servers...
var inbox = client.Inbox;
inbox.Open(FolderAccess.ReadOnly);
var results = inbox.Search(SearchOptions.All, SearchQuery.All);
foreach (var uniqueId in results.UniqueIds)
{
var message = inbox.GetMessage(uniqueId);
var sender = message.From.FirstOrDefault();
messages.Add(new IMessage() {
htmlBody = message.HtmlBody,
body = message.TextBody,
subject = message.Subject,
sender = sender == null ? "": (sender as MailboxAddress).Address,
messageID = uniqueId
});
//Mark message as read
//inbox.AddFlags(uniqueId, MessageFlags.Seen, true);
}
client.Disconnect(true);
}
return messages;
}
}
Usage:
var mail = new MailRepository("imap.gmail.com", 993, true, ConfigurationManager.AppSettings["approvalEmail"], "passwordhere")
And the program also sends email
public string SendContract()
{
//var img = Regex.Match(Request["orderscontent"], #"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
email mail = new email();
mail.server = new SmtpClient("smtp.gmail.com");
mail.server.Port = 587;
mail.server.EnableSsl = true;
mail.server.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["approvalEmail"], "passwordhere");
//mail.server.Timeout = 10000;
mail.From = new MailAddress(ConfigurationManager.AppSettings["approvalEmail"]);
mail.To.Add(Request["email"]);
mail.Subject = "DO Copy";
mail.IsBodyHtml = true;
mail.Attachments.Add(
new Attachment(
new MemoryStream(Convert.FromBase64String(Request["orderscontent"])),
string.Format("DO_copy_{0:MMddyyyyHHmm}.pdf", DateTime.Now)
)
);
mail.Send();
return "Sent!";
}
Both of the program return Error Message. But we notice when we sign in the server the program is working. But when the server is signed out it returns an error, So im not sure if the problem is from the server or the code.
I am doing an MVC application and trying to send an email to registered user for his account activation and email account verification.
Its working Fine on LocalHost but when i Deployed it on live server it gave me this error:
Error.String reference not set to an instance of a String. Parameter name: s
Following is the Code which i have written for sending email:
var verifyUrl = string.Empty;
verifyUrl = Request.Url.GetLeftPart(UriPartial.Authority) + "/Account/AccountVerify?I=" + NewUserID;
string body = "<html><head><meta content=\"text/html; charset=utf-8\" /></head><body><p>Dear " + objuserdet.Email + "" +
", </p><p>To verify your account, please click the following link:</p>"
+ "<p><a href=\"" + verifyUrl + "\" target=\"_blank\">" + verifyUrl + ""
+ "</a></p><div>Best regards,</div><div>" + NewUserID + " Team.</div><p>Note: Do not forward "
+ "this email. The verify link is private.</p></body></html>";
string To = objuserdet.Email;
string Subject = "Account Activation";
SendEmail(To,Subject,body);
and here is the Email Method:
public void SendEmail(string To, string Subject, string Body)
{
try
{
MailMessage mail = new MailMessage();
// mail.From = new MailAddress(System.Configuration.ConfigurationManager.AppSettings["EmailID"].ToString());
mail.From = new MailAddress("blue.naina9#gmail.com");
mail.To.Add(To.Trim());
mail.Subject = Subject.Trim();
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
System.Net.NetworkCredential BasicAuthenticationInfo = new System.Net.NetworkCredential("blue.naina9#gmail.com","*******");
smtp.Timeout = 600000;
smtp.UseDefaultCredentials = false;
smtp.Credentials = BasicAuthenticationInfo;
smtp.EnableSsl = true;
smtp.Send(mail);
}
catch (Exception ex)
{
throw ex;
}
}
..
Any Help will be appreciated.
Thanks
Posting stack trace would have helped. How ever the only place I think this kind of error will come is
mail.To.Add(To.Trim());
replace string To = objuserdet.Email;
with
if(!string.IsNullOrEmpty(objuserdet.Email)){
string To = objuserdet.Email;
}
else{
throw new Exception("Email is null!");
}
Check if this works!
This Error Occurs because Gmail blocks Sign-in Request of Sender Email Account From my Application due to change in my current location and Deployment server location(that is in US).
So i added a US based Account for Sending Email and it stats working Fine For me..
Hope this Help Others As well..
In my web application I have a ability to send email message, which works great when I debug it on my local machine, but since I deploy it to the server with IIS 8.5 it doesn't send email. Is there any special setting I need to do to enable smtp?
try
{
MailMessage mail = new MailMessage();
mail.To.Add(emails);
mail.From = new MailAddress("test#test.co.uk");
mail.Subject = title;
LinkedResource report = new LinkedResource(new MemoryStream(img), "image/png");
var contentId = Guid.NewGuid().ToString();
report.ContentId = contentId;
var body = "<p style='font-family:Arial, Helvetica, sans-serif, Century Gothic; font-size: 16px;'>" + content + "</p>";
body = body + string.Format("<img src=\"cid:{0}\" />", contentId);
var av1 = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
av1.LinkedResources.Add(report);
mail.AlternateViews.Add(av1);
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "mysmtphost.com";
smtp.UseDefaultCredentials = true;
smtp.Port = 25;
//smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtp.EnableSsl = false;
smtp.Send(mail);
return true;
}
catch (Exception ex)
{
Debug.Write("Execption in sendEmail:" + ex.Message);
return false;
}
I have also set up SMTP service on the server and successfully send email using PowerShell, but again I cannot send email from the app even if I change to use PickupDirectoryFromIIS (the commented one).
We have an Azure hosted website that is trying to send mail over SMTP.
All I get is timeouts, here are my POP and IMAP settings followed by code. In Azure portal under the website - do i need to configure anything in Azure website settings?
My c# code below...The code uses the following values it fetches from the database :
public bool Send(string sRecipient, string sSubject, string sBody)
{
CompanyProvider obj = _db.GetCompanyProvider();
if (!obj.EmailNotifications)
return true;
MailMessage mail = new MailMessage();
mail.To.Add(sRecipient);
mail.From = new MailAddress(obj.SenderEmail);
mail.Subject = sSubject;
string Body = sBody;
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = obj.SMTPHost;
smtp.Port = obj.SMTPPort;
smtp.Timeout = 8;
smtp.UseDefaultCredentials = false;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential(obj.SenderEmail, obj.SenderEmailPassword);// Enter senders User name and password
//smtp.Credentials = new System.Net.NetworkCredential
//(obj.SenderEmail.Substring(0, obj.SenderEmail.IndexOf('#')), obj.SenderEmailPassword);// Enter senders User name and password
try
{
smtp.Send(mail);
return true;
}
catch (Exception ex)
{
_db.writeToErrorLog(ex.ToString(), "Unable to send mail at this time");
return false;
}
}
}
When using Azure websites.....
http://azure.microsoft.com/en-in/documentation/articles/sendgrid-dotnet-how-to-send-email/
I have WSDL file which contains:
<wsdl:port name="NotificationConsumerSoapJms"
binding="tns_NotificationConsumer:NotificationConsumerSoapJmsBinding">
<jms:address destinationStyle="topic"
jndiConnectionFactoryName="ConnectionFactory"
jndiDestinationName="dynamicTopics/test.DefaultTopic">
<jms:JMSNamingProperty name="java.naming.factory.initial"
value="org.apache.activemq.jndi.ActiveMQInitialContextFactory" />
<jms:JMSNamingProperty name="java.naming.provider.url"
value="tcp://localhost:61616" />
</jms:address>
</wsdl:port>
And here is JMS client which was generated by CXF:
URL wsdlURL = EfaNbiWebService.WSDL_LOCATION;
if (args.length > 0 && args[0] != null && !"".equals(args[0])) {
File wsdlFile = new File(args[0]);
try {
if (wsdlFile.exists()) {
wsdlURL = wsdlFile.toURI().toURL();
} else {
wsdlURL = new URL(args[0]);
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
EfaNbiWebService ss = new EfaNbiWebService(wsdlURL, SERVICE_NAME);
NotificationConsumer port = ss.getNotificationConsumerSoapJms();
{
System.out.println("Invoking notify...");
org.tmforum.mtop.fmw.xsd.hdr.v1.Header _notify_mtopHeader = null;
org.tmforum.mtop.fmw.xsd.notmsg.v1.Notify _notify_mtopBody = null;
port.notify(_notify_mtopHeader, _notify_mtopBody);
}
As you see, the topic name is store in WSDL file. So how to change topic name programmatically?
I found the solution:
JMSConfiguration jmsConfig = new JMSConfiguration();
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://" + activeMQServer + ":61616");
jmsConfig.setConnectionFactory(connectionFactory);
jmsConfig.setTargetDestination("dynamicTopics/Test.Notification_" + topic);
jmsConfig.setReconnectOnException(false);
//jmsConfig.se
jmsConfig.setPubSubDomain(true);
jmsConfig.setUseJms11(true);
jmsConfig.setTransactionManager(new JmsTransactionManager(connectionFactory));
JMSConfigFeature jmsConfigFeature = new JMSConfigFeature();
jmsConfigFeature.setJmsConfig(jmsConfig);
String address = "jms:jndi:dynamicTopics/Test.Notification_" + topic + "?jndiInitialContextFactory=org.apache.activemq.jndi.ActiveMQInitialContextFactory&jndiConnectionFactoryName=ConnectionFactory&jndiURL=tcp://" + activeMQServer + ":61616";
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
// And specify the transport ID with SOAP over JMS specification
factory.setTransportId(JMSSpecConstants.SOAP_JMS_SPECIFICATION_TRANSPORTID);
factory.setServiceClass(NotificationConsumer.class);
factory.getFeatures().add(jmsConfigFeature);
factory.setAddress(address);
NotificationConsumer client = (NotificationConsumer)factory.create();
Have a nice day, guys :)