Sending email from Azure website, only timeouts, running out of ideas - asp.net-mvc

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/

Related

Sending email SMTP via GMAIL (OAUTH2 and JavaMail)

I'm using a web application through which I'm sending an email.
The SMTP host is GMAIL.
I'm using Java 1.8 and JavaMail 1.6.2.
Is there any alternative to the code written below? (credits: https://hellokoding.com/sending-email-through-gmail-smtp-server-with-java-mail-api-and-oauth-2-authorization/)
void sendMail(String smtpServerHost, String smtpServerPort, String smtpUserName, String smtpUserAccessToken, String fromUserEmail, String fromUserFullName, String toEmail, String subject, String body) {
try {
Properties props = System.getProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.port", smtpServerPort);
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(fromUserEmail, fromUserFullName));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
msg.setSubject(subject);
msg.setContent(body, "text/html");
SMTPTransport transport = new SMTPTransport(session, null);
transport.connect(smtpServerHost, smtpUserName, null);
transport.issueCommand("AUTH XOAUTH2 " + new String(BASE64EncoderStream.encode(String.format("user=%s\1auth=Bearer %s\1\1", smtpUserName, smtpUserAccessToken).getBytes())), 235);
transport.sendMessage(msg, msg.getAllRecipients());
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, ex.getMessage(), ex);
}
}
Specifically I'm very confused about these two issues:
is the following line truly the only way to set the access token in the Transport?
transport.issueCommand("AUTH XOAUTH2 " + new String(BASE64EncoderStream.encode(String.format("user=%s\1auth=Bearer %s\1\1", smtpUserName, smtpUserAccessToken).getBytes())), 235);
I've been searching throughout the web but I don't seem to find an answer, basically because every other way I've attempted has resulted in NO success.
Is it true that Google has not (yet) implemented a CLIENT credentials grant type?
How else could I send emails through my web application without the user interaction (which I don't have)?
Thank you
Try this:
//TLS and OAuth2
String address = "my.smtpserver.com";
Integer port = 587;
String user = "my_username";
String accesstoken = "my_accesstoken";
String sender = "me#mycompany.com";
String recipients = "you#yourcompany.com;someone#theircompany.com";
String subject = "Test";
String body = "This is a test.";
Properties properties = new Properties();
properties.put("mail.smtp.host", address);
properties.put("mail.smtp.port", port.toString());
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.auth.mechanisms", "XOAUTH2");
properties.put("mail.debug.auth", "true");
Session session = Session.getInstance(properties);
session.setDebug(true);
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress(sender));
String s = recipients.replace(';', ',');
mimeMessage.addRecipients(MimeMessage.RecipientType.TO,
InternetAddress.parse(s));
mimeMessage.setSubject(subject);
MimeMultipart mimeMultipart = new MimeMultipart();
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setText(body);
mimeMultipart.addBodyPart(mimeBodyPart);
mimeMessage.setContent(mimeMultipart);
Transport transport = session.getTransport();
transport.connect(user, accesstoken);
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
transport.close();
session = null;

SmtpClient not connecting when the server is sign out (Error Code: 10060)

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.

Sending emails from MVC application hosted in Azure not working

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!

Error.String reference not set to an instance of a String. Parameter name: s (While Sending Email For Account Verification in MVC4 C#)

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..

How to send email with IIS8.5

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).

Resources