I'm working on a web service to send an email. When i run my application I get the following error:
The method or operation is not implemented.
My Code in my website looks like:
WebTestServiceApp.localhost.Service1 Send = new WebTestServiceApp.localhost.Service1();
Send.Sendemail(txtTo.Text, txtSubject.Text, txtbody.Text);
My code in my webService looks like:
[WebMethod]
public string Sendemail( String inValueTo, String inValueSub, String inValueBody)
{try
{
String valueTo = inValueTo;
String valueSub = inValueSub;
String valueBody = inValueBody;
// String valueAttachmentPostedfile = inValueAttachmentPostedfile; //FileUpload1.PostedFile.FileName
// String valueAttachmentFileContent = inValueAttachemtnFileContent; //FileUpload1.FileContent.fileName
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); // Creating new message.
message.To.Add(valueTo);
message.Subject = valueSub;
message.From = new System.Net.Mail.MailAddress("shaunmossop#mweb.co.za");
message.Body = valueBody;
message.IsBodyHtml = true;
// string fileName = Path.GetFileName(valueAttachmentPostedfile); // Get attachment file
// Attachment myAttachment =
// new Attachment(valueAttachmentFileContent, fileName);
// if (fileName != "")
// {
// message.Attachments.Add(myAttachment); // Send attachment
// }
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com"); //Properties.Settings.Default.MailSMTPServer
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
NetworkCredential netC = new NetworkCredential(Properties.Settings.Default.username, Properties.Settings.Default.password); // Useing Projects defult settings.
smtp.Credentials = netC;
smtp.Send(message);
return "Message has been sent";
}
catch (Exception)
{
return "Message faild to send" ;
}}
The rest of the code in the webService works, i know this because i used it in a working website, my problem is just passing the values though or a step i'm missing in the webService.
Can anyone see a obvious problem and what am i doing wrong, iv used webservices in VB but not C# so is there a difference?
It could be possible that the Web Reference has not been updated for your current application and hence it might be linking to the case wherein the method was not implemented.
So the only way to get it checked and working would be to Try update the Web Reference.
Related
So I'm trying to add an attachment when I send an email, but I am not sure how. The email works perfectly fine, but it's the adding onto the attachment for the email which doesn't work. I'm not trying to use any specific platform and just sending it via through the console essentially. I tried msgObj.attachments1.add(...) but it didn't work with it.
using (SmtpClient client = new SmtpClient("10.10.101.10", 500))
{
client.EnableSsl = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(username,password);// has username and password credentials doesnt contain actual username and pass
MailMessage msgObj = new MailMessage();
List<string> attachments1 = new List<string>();
attachments1.Add(#"C:\Users -test.xlsx");
msgObj.IsBodyHtml = true; //always sets true, if the body contains html it turns text to html
msgObj.To.Add(Destination);
msgObj.From = new MailAddress("test#mail.com"); //you can send emails on behalf of somebody
msgObj.Subject = YourMessageSubject;
// msgObj.Body = YourMessageBody; //need to edit the body remember to use the message body to call upon it
msgObj.Body = messageBody2; //html
client.Send(msgObj); // sends the message
}
}
catch (Exception)
{
Console.WriteLine("somethings broken");
}
Try attaching it:
msgObj.Attachments.Add(new Attachment(#"C:\Users -test.xlsx"));
I'm trying to send mail using SendGrid but I can't. It always throws an exception that I can't fix.
How do I to fix this issue ?
SendMail
public static Boolean isSend(IList<String> emailTo, String mensagem, String assunto, String emailFrom, String emailFromName){
try{
MailMessage mail = new MailMessage();
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.SubjectEncoding = System.Text.Encoding.UTF8;
//to
foreach (String e in emailTo) {
mail.To.Add(e);
}
mail.From = new MailAddress(emailFrom);
mail.Subject = assunto;
mail.Body = mensagem;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = CustomEmail.SENDGRID_SMTP_SERVER;
smtp.Port = CustomEmail.SENDGRID_PORT_587;
smtp.Credentials = new System.Net.NetworkCredential(CustomEmail.SENDGRID_API_KEY_USERNAME, CustomEmail.SENDGRID_API_KEY_PASSWORD);
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = false;
smtp.Timeout = 20000;
smtp.Send(mail);
return true;
}catch (SmtpException e){
Debug.WriteLine(e.Message);
return false;
}
}
CustomMail
//SendGrid Configs
public const String SENDGRID_SMTP_SERVER = "smtp.sendgrid.net";
public const int SENDGRID_PORT_587 = 587;
public const String SENDGRID_API_KEY_USERNAME = "apikey"; //myself
public const String SENDGRID_API_KEY_PASSWORD = "SG.xx-xxxxxxxxxxxxxxxxxxxxxxxxx-E";
Exception
Exception thrown: 'System.Net.Mail.SmtpException' in System.dll
Server Answer: Unauthenticated senders not allowed
For sending emails with SendGrid there is v3 API. The NuGet name is SendGrid and the link is here.
This library does not work with System.Net.Mail.MailMessage, it uses SendGrid.Helpers.Mail.SendGridMessage.
This library uses an API key for authorization. You can create one when you log into SendGrid web app, and navigate to Email API -> Integration Guide -> Web API -> C#.
var client = new SendGridClient(apiKey);
var msg = MailHelper.CreateSingleTemplateEmail(from, new EmailAddress(to), templateId, dynamicTemplateData);
try
{
var response = client.SendEmailAsync(msg).Result;
if (response.StatusCode != HttpStatusCode.OK
&& response.StatusCode != HttpStatusCode.Accepted)
{
var errorMessage = response.Body.ReadAsStringAsync().Result;
throw new Exception($"Failed to send mail to {to}, status code {response.StatusCode}, {errorMessage}");
}
}
catch (WebException exc)
{
throw new WebException(new StreamReader(exc.Response.GetResponseStream()).ReadToEnd(), exc);
}
I think your problem stems from not instantiating the SMTP client with the server in the constructor. Also you should wrap your smtpclient in a using statement so it disposes of it properly, or call dispose once you're finished.
Try this:
public static Boolean isSend(IList<String> emailTo, String mensagem, String assunto, String emailFrom, String emailFromName)
{
try
{
MailMessage mail = new MailMessage();
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.SubjectEncoding = System.Text.Encoding.UTF8;
//to
foreach (String e in emailTo)
{
mail.To.Add(e);
}
mail.From = new MailAddress(emailFrom);
mail.Subject = assunto;
mail.Body = mensagem;
mail.IsBodyHtml = true;
using(SmtpClient smtp = new SmtpClient(CustomEmail.SENDGRID_SMTP_SERVER)){
smtp.Port = CustomEmail.SENDGRID_PORT_587;
smtp.Credentials = new System.Net.NetworkCredential(CustomEmail.SENDGRID_API_KEY_USERNAME, CustomEmail.SENDGRID_API_KEY_PASSWORD);
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = false;
smtp.Timeout = 20000;
smtp.Send(mail)
}
}
catch (SmtpException e)
{
Debug.WriteLine(e.Message);
return false;
}
}
If that doesn't work you could try removing the port, enablessl and usedefaultcredentials parameters for the smtp client. I use sendgrid all the time and don't use those options.
To more specifically answer your original question and the cause of your exception, the SendGrid SMTP server probably isn't looking for your account's username and password, but rather your API key. The error seems to indicate your authentication is not successful.
https://sendgrid.com/docs/for-developers/sending-email/v3-csharp-code-example/
To integrate with SendGrids SMTP API:
Create an API Key with at least "Mail" permissions.
Set the server host in your email client or application to smtp.sendgrid.net.
This setting is sometimes referred to as the external SMTP server or the SMTP relay.
Set your username to apikey.
Set your password to the API key generated in step 1.
Set the port to 587.
Using the SendGrid C# library will also simplify this process:
https://sendgrid.com/docs/for-developers/sending-email/v3-csharp-code-example/
// using SendGrid's C# Library
// https://github.com/sendgrid/sendgrid-csharp
using SendGrid;
using SendGrid.Helpers.Mail;
using System;
using System.Threading.Tasks;
namespace Example
{
internal class Example
{
private static void Main()
{
Execute().Wait();
}
static async Task Execute()
{
var apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY");
var client = new SendGridClient(apiKey);
var from = new EmailAddress("test#example.com", "Example User");
var subject = "Sending with SendGrid is Fun";
var to = new EmailAddress("test#example.com", "Example User");
var plainTextContent = "and easy to do anywhere, even with C#";
var htmlContent = "<strong>and easy to do anywhere, even with C#</strong>";
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
var response = await client.SendEmailAsync(msg);
}
}
}
This is a class from my code.
string to = message.Text;
string from = "noreply#zayzaycorporation.onmicrosoft.com";
MailMessage messagex = new MailMessage(from, to);
string mailbody = "Welcome!";
messagex.Subject = "Hello";
messagex.Body = mailbody;
messagex.Attachments.Add(new System.Net.Mail.Attachment("C:\\doc\\start.pdf"));
messagex.BodyEncoding = Encoding.UTF8;
messagex.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.office365.com", 587);
System.Net.NetworkCredential basicCredential1 = new
System.Net.NetworkCredential("noreply#zayzaycorporation.onmicrosoft.com", "XXX");
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = basicCredential1;
client.Send(messagex);
context.Done(string.Empty);
The class sends the email with an attachment, works good. But my problem is when it's published as a Web Service in azure because there doesn't find any folder named "doc" on "C:\\". How can it be referenced the attachment to a folder from the main solution?
Thanks.
The Attachment class can be constructed using a Stream, which can thus contain anything and come from anywhere.
So basically generate the attachment in memory and wrap it in a MemoryStream or similar.
Try this..
String path = Application.StartupPath + "\doc\test.xml";
I develop a program to send emails automatically using c#, and I want to insert a link to a web site to that email. How can I do it?
public bool genarateEmail(String from, String to, String cc, String displayName,
String password, String subjet, String body)
{
bool EmailIsSent = false;
MailMessage m = new MailMessage();
SmtpClient sc = new SmtpClient();
try
{
m.From = new MailAddress(from, displayName);
m.To.Add(new MailAddress(to, displayName));
m.CC.Add(new MailAddress("xxx#gmail.com", "Display name CC"));
m.Subject = subjet;
m.IsBodyHtml = true;
m.Body = body;
sc.Host = "smtp.gmail.com";
sc.Port = 587;
sc.Credentials = new
System.Net.NetworkCredential(from, password);
sc.EnableSsl = true;
sc.Send(m);
EmailIsSent = true;
}
catch (Exception ex)
{
EmailIsSent = false;
}
return EmailIsSent;
}
I want to send a link through this email. How should I add it to email?
You should be able to just add the mark-up for the link in your body variable:
body = "blah blah <a href='http://www.example.com'>blah</a>";
You shouldn't have to do anything special since you're specifying your body contains HTML (m.IsBodyHtml = true).
String body = "Your message : <a href='http://www.example.com'></a>"
m.Body = body;
Within the body. This will require that the body be constructed as HTML so the that a or can be used to render your link. You can use something like StringTemplate to generate the html including your link.
For some dynamic links, the email service providers will not show your link into email body if the link not prepend http (security issues)
like localhost:xxxx/myPage
m.body = "<a href='http://" + Request.Url.Authority + "/myPage'>click here</a>"
I am using mail message class to send an email. But if i check my Gmail account, mail is received as separate mail. I want mails in a single thread. I am also using the same subject and tried appending "Re: " before subject. it did not work for me.
I will be pleased if get the solution. following is the code I am using.
public static bool SendEmail(
string pGmailEmail,
string pGmailPassword,
string pTo,
string pFrom,
string pSubject,
string pBody,
System.Web.Mail.MailFormat pFormat,
string pAttachmentPath)
{
try
{
System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpserver",
"smtp.gmail.com");
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpserverport",
"465");
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendusing",
"2");
//sendusing: cdoSendUsingPort, value 2, for sending the message using
//the network.
//smtpauthenticate: Specifies the mechanism used when authenticating
//to an SMTP
//service over the network. Possible values are:
//- cdoAnonymous, value 0. Do not authenticate.
//- cdoBasic, value 1. Use basic clear-text authentication.
//When using this option you have to provide the user name and password
//through the sendusername and sendpassword fields.
//- cdoNTLM, value 2. The current process security context is used to
// authenticate with the service.
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
//Use 0 for anonymous
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendusername",
pGmailEmail);
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendpassword",
pGmailPassword);
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpusessl",
"true");
myMail.From = pFrom;
myMail.To = pTo;
myMail.Subject = pSubject;
myMail.BodyFormat = pFormat;
myMail.Body = pBody;
if (pAttachmentPath.Trim() != "")
{
MailAttachment MyAttachment =
new MailAttachment(pAttachmentPath);
myMail.Attachments.Add(MyAttachment);
myMail.Priority = System.Web.Mail.MailPriority.High;
}
// System.Web.Mail.SmtpMail.SmtpServer = CCConstants.MAIL_SERVER;
System.Web.Mail.SmtpMail.Send(myMail);
return true;
}
catch
{
throw;
}
}
you should know thread starter email internal ID, then you should send it back via headers "In-Reply-To: " or "References: ".
Btw sending email via gmail is rather simple:
var smtpClient = new SmtpClient("smtp.gmail.com",587);
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential("USERNAME#gmail.com"
,"PASSWORD");
using (MailMessage message = new MailMessage("USERNAME#gmail.com","USERNAME#gmail.com"))
{
message.Subject = "test";
smtpClient.Send(message);
}
using (MailMessage message = new MailMessage("USERNAME#gmail.com","USERNAME#gmail.com"))
{
message.Subject = "Re: test";
message.Headers.Add("In-Reply-To", "<MESSAGEID.From.Original.Message>");
message.Headers.Add("References", "<MESSAGEID.From.Original.Message>");
smtpClient.Send(message);
}