This is very very strange.
Basically, i'm using ASP.NET. What I want is to get the .Text value from a label.
Initially, the label is actually totally empty. However, after some interaction and some clicks etc, the label changes.
Now.... I want to simply access the content of that specific label...BUT....ASP.NET thinks it's content is STILL empty.
As a test, I changed the content of the label in to something obvious like "lol", for example.
Then I did the procedure again. Now....This time, the results for checking the contents after all of the interaction and clicks etc turned out to be "lol"...
This means that ASP isn't keeping track of current changes. It just keeps in mind what the initial values were.
The reason why I am checking the contents is because I wish to send an email. Below is my code:
MailMessage email = new MailMessage();
email.Subject = "****";
email.To.Add(txtEmailTo.Text);
email.From = new MailAddress("****");
email.IsBodyHtml = true;
string emailBody = "<h2>Journey Details</h2><br><strong>From</strong>: %From%<br><strong>To</strong>: %To%<br><strong>Price</strong>: %Price%<br><hr><br>Kind Regards, <br><br>";
String newBody = emailBody;
newBody.Replace("%From%", lblResultsFrom.Text);
email.Body = newBody;
try
{
SMTPServer.Send(email);
}
catch (Exception ex)
{
lblError.Text = ex.ToString();
}
First, use String.Format() instead of manually replacing string fragments, if possible.
How do you change the label's text? Are you doing it at client side with JavaScript? The text of an html label, span, bold, and lot of tags is not sent back to the server. If you want to change the value of something, and send it back to the server, that must be a textbox, or textarea. Or you would have to use hand coded JavaScript to send the value, and custom server side logic to get the value.
I managed to fix my code. The following works:
var SMTPServer = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential("..", "..."),
};
MailMessage email = new MailMessage();
email.Subject = "...";
email.To.Add(txtEmailTo.Text);
email.From = new MailAddress("..");
email.IsBodyHtml = true;
string emailBody = "...";
String newBody = emailBody;
email.Body = newBody;
try
{
SMTPServer.Send(email);
}
catch (Exception ex)
{
lblError.Text = ex.ToString();
}
Related
Novice developer here with an issue I would appreciate some assistance with :-)
I am developing an ASP web application (a simple bulletin board, which allows users to create buy and sale adverts). All of my data is being stored/retrieved from an MSSQL database. However, I wish to store/retrieve images for the adverts using a SharePoint Online library.
I am struggling at the first hurdle, which is uploading the image to the library. I've debugged and debugged some more but I am still hitting a brick wall. After many hours of trying, I now have the code below, which is no longer returning any errors although the image never appears in the destination library.
Given all the above, I would sincerely appreciate any assistance from any experts out there!
The following code fires when the "create advert" button is pressed.
string currentUserName =
System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName;
SqlConnection conn2;
SqlCommand comm2;
SqlDataReader reader;
string connectionString2 =
ConfigurationManager.ConnectionStrings["CCString"].ConnectionString;
conn2 = new SqlConnection(connectionString2);
comm2 = new SqlCommand("SELECT TOP 1 * FROM Threads WHERE ([AdvertiserName] = '" + currentUserName + "') ORDER BY PostCreationDateTime DESC", conn2);
conn2.Open();
reader = comm2.ExecuteReader();
reader.Read();
Guid imageID;
string imageIDConfirmed = "";
string fileExtension = "";
if (reader["UniqueImageID"].GetType().Name != "DBNull")
{
imageID = (Guid)reader["UniqueImageID"];
imageIDConfirmed = imageID.ToString().Replace(":", "-");
string myFile = jpgFileUpload.FileName;
fileExtension = myFile.Substring(myFile.Length - 4, 4);
}
reader.Close();
conn2.Close();
string username = "username#emailaddress.com";
string password = "password";
System.Security.SecureString securePass = new
System.Security.SecureString();
foreach (char ch in password.ToCharArray()) securePass.AppendChar(ch);
SharePointOnlineCredentials credentials = new
SharePointOnlineCredentials(username, securePass);
using (ClientContext client = new
ClientContext("https://company.sharepoint.com/sites/SiteName/"))
{
var formLib = client.Web.Lists.GetByTitle("Documents");
client.Credentials = credentials;
client.Load(formLib.RootFolder);
client.ExecuteQuery();
string fileName = #"C:\Temp\" + jpgFileUpload.FileName;
jpgFileUpload.SaveAs(fileName);
var fileUrl = "";
int fileLen;
fileLen = jpgFileUpload.PostedFile.ContentLength;
byte[] input = new byte[fileLen - 1];
input = jpgFileUpload.FileBytes;
UploadDocument(#"https://company.sharepoint.com/sites/SiteName/", "Documents", "https://company.sharepoint.com/sites/SiteName/Shared%20Documents/", "testDocument", input);
using (var fs = new FileStream(fileName, FileMode.Open))
{
var fi = new FileInfo(imageIDConfirmed + fileExtension);
fileUrl = String.Format("{0}/{1}", formLib.RootFolder.ServerRelativeUrl, fi.Name);
Microsoft.SharePoint.Client.File.SaveBinaryDirect(client, fileUrl, fs, true);
client.ExecuteQuery();
}
var libFields = formLib.Fields;
client.Load(libFields);
client.ExecuteQuery();
Microsoft.SharePoint.Client.File newFile =
client.Web.GetFileByServerRelativeUrl(fileUrl);
Microsoft.SharePoint.Client.ListItem item = newFile.ListItemAllFields;
item["Title"] = "Any Title";
item["File Name"] = "Any File Name";
item.Update();
client.Credentials = credentials;
client.ExecuteQuery();
which is no longer returning any errors although the image never appears in the destination library
Is it possible that the files are there but are in some unchecked-in state?
As a site collection admin, go to Documents -> Settings -> "Permissions and Management" section -> Manage files which have no checked in version.
If there are files with no checked in version, this could indicate the need to provide check-in logic in your code, or there might be an issue with required fields.
I have a asp.net MVC 3 web application, where in some page I am showing a bar chart.
Now user is asking a "mailto" kind of link in that page and on clicking of that link, email client should open, where TO, Subject & Body will fill automatically and the bar chart should appear in body.
I know there is limitation of "mailto", we can prepare body with simple text like below, but is there any workaround to put graph within email body?
Check Mail
The mailto protocol is pretty limited. You might need to send the email from your server.
using Microsoft.Office.Interop.Outlook;
public void Sendemail()
{
try
{
Application oApp = new Application();
MailItem oMsg = (MailItem)(oApp.CreateItem(OlItemType.olMailItem));
// Set HTMLBody.
const string emailSubject = "Auto Generated Email:Graph Screen Shot Update for";
const string sDisplayName = "MyAttachment";
const int iPosition = 50; //
const int iAttachType = (int)OlAttachmentType.olByValue;
string htmlStart = "<html><body><h5><Font Color=Purpel>Hi,<br/>Please Find below The screen shot as of " + DateTime.Now + "<br/></h5>";
string body = string.Empty;
Microsoft.Office.Interop.Outlook.Attachment oAttach = oMsg.Attachments.Add(#"c:\Apps\download.jpg", iAttachType, iPosition, sDisplayName);
body += "<img src=\"cid:" + oAttach.FileName + "\" /><br/>";
string wholeBody = htmlStart + body + "<h5><Font Color=Purpel>Note:Please check the graph.<br/>Regards,<br/>Md. Ajmal<br/><br/></h5></body></html>";
oMsg.HTMLBody = wholeBody;
// Set the subject.
oMsg.Subject = emailSubject;
//display
oMsg.Display(oMsg);
// Clean up.
oMsg = null;
oApp = null;
}
catch (System.Exception ex)
{
throw ex;
}
}
I created Intranet project which connect with AD to retrieve User's
data as Image , Department . I did my code and it works well but I had
the below error a lot of times .
string User = ConfigurationManager.AppSettings["User"];
string Password = ConfigurationManager.AppSettings["Password"];
var entry = new DirectoryEntry("LDAP://" + "xxxxx", User, Password);
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.SearchScope = SearchScope.Subtree;
string UserName = Page.User.Identity.Name;
searcher.Filter = string.Format(CultureInfo.InvariantCulture, "(sAMAccountName={0})", UserName.Split('\\')[1]);
SearchResult findUser = searcher.FindOne();
if (findUser != null)
{
DirectoryEntry user = findUser.GetDirectoryEntry();
//string loginuser = user.Properties["UserName"].Value.ToString();
LoggedUser = user.Properties["displayName"].Value.ToString();
Session.Add("LoggedUser", LoggedUser);
LoggedEmail = user.Properties["mail"].Value.ToString();
Session.Add("LoggedEmail", LoggedEmail);
string Mobile = user.Properties["Mobile"] != null && user.Properties["Mobile"].Value != null ? user.Properties["Mobile"].Value.ToString() : null;
string Login = user.Properties["sAMAccountName"].Value.ToString();
if (user.Properties["Department"].Value != null)
LoggedDepartement = user.Properties["Department"].Value.ToString();
_userDept = user.Properties["Department"].Value != null ? user.Properties["Department"].Value.ToString() : "";
ftier.AddLoggedUser(LoggedUser, LoggedDepartement, title, LoggedEmail, data, DateTime.Now, DateTime.Now, " nnnnn", true);
When I've done this in the past one of the problems was unusual characters in the properties of the user object caused this sort of error.
One approach would be to put error checking on each of the variables you're setting so the code can keep working, or export to a text file all the data and go through it using excel and look for unusual or strange control characters.
If the error always occurs at a certain person you could just look at the properties of that user and hope to find the issue that way.
Our issue was the use of Chinese simplified characters in some fields.
Hope this helps you track down your issue.
Dorje
I host my web app which is written in .net mvc2 on amazon ec2. currrently use gmail smtp to send email. beacuse of google for startup email quota cant send more than 500 email a day. So decide to move amazon ses. How can use amazon ses with asp.net mvc2? How about configuration etc? Is email will send via gmail? because our email provider is gmail. etc.
Send Email via Amazon is a right decision. Because when you move to amazon you will immediately get 2000 email free per day which is greater than googla apps 500 emails quota a day.
Step by Step:
Go to http://aws.amazon.com/ses
and click Sign Up for Amazon SES.
To get your AWS access identifiers
verify your email address - email
which you will send email via. You
need perl packages installled on
your computer to test email
features.
include:amazonses.com to your dns record.
Step by step documentation.
http://docs.aws.amazon.com/ses/latest/DeveloperGuide/getting-started.html
There is a Amazon SES (Simple Email Service) C# Wrapper on codeplex you can use this wrapper to send emails.
Amazon SES C# Wrapper
Easiest way is to download the SDK via Nuget (package is called AWSSDK) or download the SDK from Amazon's site. The sdk download from their site has an example project that shows you how to call their API to send email. The only configuration is plugging in your api keys. The trickiest part is verifying your send address (and any test receipients) but their is an API call there too to send the test message. You will then need to log in and verify those email addresses. The email will be sent through Amazon (that is the whole point) but the from email address can be your gmail address.
#gandil I created this very simple code to send emails
using Amazon;
using Amazon.SimpleEmail;
using Amazon.SimpleEmail.Model;
using System.IO;
namespace SendEmail
{
class Program
{
static void Main(string[] args)
{
//Remember to enter your (AWSAccessKeyID, AWSSecretAccessKey) if not using and IAM User with credentials assigned to your instance and your RegionEndpoint
using (var client = new AmazonSimpleEmailServiceClient("YourAWSAccessKeyID", "YourAWSSecretAccessKey", RegionEndpoint.USEast1))
{
var emailRequest = new SendEmailRequest()
{
Source = "FROMADDRESS#TEST.COM",
Destination = new Destination(),
Message = new Message()
};
emailRequest.Destination.ToAddresses.Add("TOADDRESS#TEST.COM");
emailRequest.Message.Subject = new Content("Hello World");
emailRequest.Message.Body = new Body(new Content("Hello World"));
client.SendEmail(emailRequest);
}
}
}
}
You can find the code in here https://github.com/gianluis90/amazon-send-email
Download AWSSDK.dll file from internet
use following name-spaces
using Amazon;
using Amazon.SimpleEmail;
using Amazon.SimpleEmail.Model;
using System.Net.Mail;
2 . Add to web config...
<appSettings>
<add key="AWSAccessKey" value="Your AWS Access Key" />
<add key="AWSSecretKey" value="Your AWS secret Key" />
</appSettings>
3 . Add a AWSEmailSevice class to your project that will allow to send mail via AWS ses...
public class AWSEmailSevice
{
//create smtp client instance...
SmtpClient smtpClient = new SmtpClient();
//for sent mail notification...
bool _isMailSent = false;
//Attached file path...
public string AttachedFile = string.Empty;
//HTML Template used in mail ...
public string Template = string.Empty;
//hold the final template data list of users...
public string _finalTemplate = string.Empty;
//Template replacements varibales dictionary....
public Dictionary<string, string> Replacements = new Dictionary<string, string>();
public bool SendMail(MailMessage mailMessage)
{
try
{
if (mailMessage != null)
{
//code for fixed things
//from address...
mailMessage.From = new MailAddress("from#gmail.com");
//set priority high
mailMessage.Priority = System.Net.Mail.MailPriority.High;
//Allow html true..
mailMessage.IsBodyHtml = true;
//Set attachment data..
if (!string.IsNullOrEmpty(AttachedFile))
{
//clear old attachment..
mailMessage.Attachments.Clear();
Attachment atchFile = new Attachment(AttachedFile);
mailMessage.Attachments.Add(atchFile);
}
//Read email template data ...
if (!string.IsNullOrEmpty(Template))
_finalTemplate = File.ReadAllText(Template);
//check replacements ...
if (Replacements.Count > 0)
{
//exception attached template..
if (string.IsNullOrEmpty(_finalTemplate))
{
throw new Exception("Set Template field (i.e. file path) while using replacement field");
}
foreach (var item in Replacements)
{
//Replace Required Variables...
_finalTemplate = _finalTemplate.Replace("<%" + item.Key.ToString() + "%>", item.Value.ToString());
}
}
//Set template...
mailMessage.Body = _finalTemplate;
//Send Email Using AWS SES...
var message = mailMessage;
var stream = FromMailMessageToMemoryStream(message);
using (AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(
ConfigurationManager.AppSettings["AWSAccessKey"].ToString(),
ConfigurationManager.AppSettings["AWSSecretKey"].ToString(),
RegionEndpoint.USWest2))
{
var sendRequest = new SendRawEmailRequest { RawMessage = new RawMessage { Data = stream } };
var response = client.SendRawEmail(sendRequest);
//return true ...
_isMailSent = true;
}
}
else
{
_isMailSent = false;
}
}
catch (Exception ex)
{
throw ex;
}
return _isMailSent;
}
private MemoryStream FromMailMessageToMemoryStream(MailMessage message)
{
Assembly assembly = typeof(SmtpClient).Assembly;
Type mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");
MemoryStream stream = new MemoryStream();
ConstructorInfo mailWriterContructor =
mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream) }, null);
object mailWriter = mailWriterContructor.Invoke(new object[] { stream });
MethodInfo sendMethod =
typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic);
if (sendMethod.GetParameters().Length == 3)
{
sendMethod.Invoke(message, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true, true }, null); // .NET 4.x
}
else
{
sendMethod.Invoke(message, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true }, null); // .NET < 4.0
}
MethodInfo closeMethod =
mailWriter.GetType().GetMethod("Close", BindingFlags.Instance | BindingFlags.NonPublic);
closeMethod.Invoke(mailWriter, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { }, null);
return stream;
}
}
Use above class to send mail anyone with attachment and template varibales replacement (it's optional)
// Call this method to send your email
public string SendEmailViaAWS()
{
string emailStatus = "";
//Create instance for send email...
AWSEmailSevice emailContaint = new AWSEmailSevice();
MailMessage emailStuff = new MailMessage();
//email subject..
emailStuff.Subject = "Your Email subject";
//region Optional email stuff
//Templates to be used in email / Add your Html template path ..
emailContaint.Template = #"\Templates\MyUserNotification.html";
//add file attachment / add your file ...
emailContaint.AttachedFile = "\ExcelReport\report.pdf";
//Note :In case of template
//if youe want to replace variables in run time
//just add replacements like <%FirstName%> , <%OrderNo%> , in HTML Template
//if you are using some varibales in template then add
// Hold first name..
var FirstName = "User First Name";
// Hold email..
var OrderNo = 1236;
//firstname replacement..
emailContaint.Replacements.Add("FirstName", FirstName.ToString());
emailContaint.Replacements.Add("OrderNo", OrderNo.ToString());
// endregion option email stuff
//user OrderNo replacement...
emailContaint.To.Add(new MailAddress("TOEmail#gmail.com"));
//mail sent status
bool isSent = emailContaint.SendMail(emailStuff);
if(isSent)
{
emailStatus = "Success";
}
else
{
emailStatus = "Fail";
}
return emailStatus ; }
Following is how I sent email with attachment
public static void SendMailSynch(string file1, string sentFrom, List<string> recipientsList, string subject, string body)
{
string smtpClient = "email-smtp.us-east-1.amazonaws.com"; //Correct it
string conSMTPUsername = "<USERNAME>";
string conSMTPPassword = "<PWD>";
string username = conSMTPUsername;
string password = conSMTPPassword;
// Configure the client:
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(smtpClient);
client.Port = 25;
client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(username, password);
client.EnableSsl = true;
client.Credentials = credentials;
// Create the message:
var mail = new System.Net.Mail.MailMessage();
mail.From = new MailAddress(sentFrom);
foreach (string recipient in recipientsList)
{
mail.To.Add(recipient);
}
mail.Bcc.Add("test#test.com");
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
Attachment attachment1 = new Attachment(file1, MediaTypeNames.Application.Octet);
ContentDisposition disposition = attachment1.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file1);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file1);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file1);
mail.Attachments.Add(attachment1);
client.Send(mail);
}
Im working on a legacy app that has this logic in its code that I cant modify unfortunately. I have the proper settings in the web.config and was wondering if i list the proper SMTP server would the web.config settings take care of the credentials?
If not what options do i have for sending email out with this code?
string str13 = "";
str13 = StringType.FromObject(HttpContext.Current.Application["MailServer"]);
if (str13.Length > 2)
{
SmtpMail.SmtpServer = str13;
}
else
{
SmtpMail.SmtpServer = "localhost";
}
SmtpMail.Send(message);
System.Web.Mail does not expose any settings for specifying credentials, unfortunately. It is possible to send authenticated emails, though, because System.Web.Mail is built on top of CDOSYS. Here's a KB article which describes how to do it, but you basically have to modify some properties on the message itself:
var msg = new MailMessage();
if (userName.Length > 0)
{
string ns = "http://schemas.microsoft.com/cdo/configuration/";
msg.Fields.Add(ns + "smtpserver", smtpServer);
msg.Fields.Add(ns + "smtpserverport", 25) ;
msg.Fields.Add(ns + "sendusing", cdoSendUsingPort) ;
msg.Fields.Add(ns + "smtpauthenticate", cdoBasic);
msg.Fields.Add(ns + "sendusername", userName);
msg.Fields.Add(ns + "sendpassword", password);
}
msg.To = "someone#domain.com";
msg.From = "me#domain.com";
msg.Subject = "Subject";
msg.Body = "Message";
SmtpMail.Send(msg);
Whether that works for your situation or not, I'm not sure....