How can I add an attachment to a MailMessage? - smtp

I've got this code that sends a simple email using SmtpClient, MailMessage, and MailAddress objects:
private void EmailMessage(string msg)
{
string TO_EMAIL = "cshannon#proactusa.com";
var windowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent();
string userName = windowsIdentity.Name;
string subject = string.Format("Log msg from Report Runner app sent {0}; user was {1}", DateTime.Now.ToLongDateString(), userName);
string body = msg;
var SmtpServer = new SmtpClient(ReportRunnerConstsAndUtils.EMAIL_SERVER);
var SendMe = new MailMessage();
SendMe.To.Add(TO_EMAIL);
SendMe.Subject = subject;
SendMe.From = new MailAddress(ReportRunnerConstsAndUtils.FROM_EMAIL);
SendMe.Body = body;
try
{
SmtpServer.UseDefaultCredentials = true;
SmtpServer.Send(SendMe);
}
}
I also need, though, to attach a file to an email. I was doing it using Outlook like so:
Application app = new Application();
MailItem mailItem = app.CreateItem(OlItemType.olMailItem);
. . .
FileInfo[] rptsToEmail = GetLastReportsGenerated();
foreach (var file in rptsToEmail)
{
String fullFilename = String.Format("{0}\\{1}", uniqueFolder, file.Name);
if (!file.Name.Contains(PROCESSED_FILE_APPENDAGE))
{
mailItem.Attachments.Add(fullFilename);
}
}
mailItem.Importance = OlImportance.olImportanceNormal;
mailItem.Display(false);
...but I need to move away from using Outlook for this. Here the MailItem is a Microsoft.Office.Interop.Outlook.MailItem
How can I add attachments in the simple MailMessage I need to use now?
Setting the Importance is not too important, I don't think, but the Display is something I will need to set for the MailMessage, too.

Easy:
if (!file.Name.Contains(PROCESSED_FILE_APPENDAGE))
{
var attachment = new Attachment(fullFilename);
mailMsg.Attachments.Add(attachment);
}
mailMsg.Priority = MailPriority.Normal;

Related

Send an email with a file and each time the file name is with the current time

I have a task for executions to send a file that has been downloaded from the database
and I will have to send the file by e-mail with the name of the time the file was sent.
what would be the order of execution of this task in integrated services
with the use of file system task and send email task in ssis.
No doubt, you should create your with file system task at first and save it where you wish. after that with using "Script Task" in control flow, you can send it easily. You just add these sources in "using namespaces" block:
"using System.Net.Mail;"
The Code you need to add in public main method should be like this:
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
string sSubject = [Your Subject Name String];
string sBody = [Your Body String];
string sEmailServer = [The Address of your Email Server];
string sEmailPort = [The Email Port];
string sEmailUser = [Your Email address];
string sEmailPassword = [Your Email Password];
string sEmailSendTo = [The Receiver Email];
string sEmailSendCC = [The CC Sender Email];
string sEmailSendFrom = [The Sender Email];
string sEmailSendFromName = [The Sender Name];
message.Priority = MailPriority.High;(Normal, Low, High).
MailAddress fromAddress = new MailAddress(sEmailSendFrom, sEmailSendFromName);
message.From = fromAddress;
string[] sEmailTo = Regex.Split(sEmailSendTo, ";");
string[] sEmailCC = Regex.Split(sEmailSendCC, ";");
int sEmailServerSMTP = int.Parse(sEmailPort);
smtpClient.Host = sEmailServer;
smtpClient.Port = sEmailServerSMTP;
smtpClient.EnableSsl = false;
System.Net.NetworkCredential myCredentials =
new System.Net.NetworkCredential(sEmailUser, sEmailPassword);
smtpClient.Credentials = myCredentials;
if (sEmailTo != null)
{
for (int i = 0; i < sEmailTo.Length; ++i)
{
if (sEmailTo[i] != null && sEmailTo[i] != "")
{
message.To.Add(sEmailTo[i]);
}
}
}
if (sEmailCC != null)
{
for (int i = 0; i < sEmailCC.Length; ++i)
{
if (sEmailCC[i] != null && sEmailCC[i] != "")
{
message.To.Add(sEmailCC[i]);
}
}
}
Attachment myAttachment = new Attachment([The path the file you saved]);
message.Attachments.Add(myAttachment);
message.Subject = sSubject;
message.IsBodyHtml = false;
message.Body = sBody;
smtpClient.Send(message);

AegisImplicitMail asp.net html body email

I am trying to send mail in asp.net whit AegisImplicitMail. My code is:
string OggettoEmailIta = "Oggetto email";
string TestoEmailIta = "<p>aaa</p><br/><div>bbb</div>";
var mailMessage = new MimeMailMessage();
mailMessage.Subject = OggettoEmailIta;
mailMessage.IsBodyHtml = true;
mailMessage.Body = TestoEmailIta;
mailMessage.Sender = new MimeMailAddress("XXX", "XXX");
mailMessage.From = new MimeMailAddress("XXX", "XXX");
mailMessage.To.Add(new MimeMailAddress("XXX", "XXX"));
mailMessage.To.Add(new MimeMailAddress("XXX", "XXX"));
var emailer = new SmtpSocketClient();
emailer.Host = "smtp.XXX.XX";
emailer.Port = 465;
emailer.SslType = SslMode.Ssl;
emailer.User = "XXX";
emailer.Password = "XXX";
emailer.AuthenticationMode = AuthenticationType.Base64;
emailer.MailMessage.IsBodyHtml = true;
emailer.MailMessage = mailMessage;
emailer.SendMailAsync();
The mail is sent correctly but it is not in HTML format.
Can someone help me?
you might try string literals "#" for your html message, so all chars are kept
string TestoEmailIta = #"<p>aaa</p><br/><div>bbb</div>";

ASP.Net 2013 MVC 5 insert record and sends email with link to the record just created

I have setup an asp.net MVC project that inserts a record and then grabs the url information to be sent via email of which is a link in the body of the email. I would like to be able to pass the location of the details page with the id of the record if that makes sense? I am just not sure how to capture the full path and the id that I just created in the insert of the record just submitted. Can any one please help me on this. It would be greatly appreciated. This is my code and I need the url and id to be in the body of the email upon submit:
[HttpPost]
public ActionResult NewHire([Bind(Include = "ID,Manager,HR_Emp,Emp_FirstName,Emp_LastName,Emp_StartDate,Emp_OfficeLocation,Emp_Department,Emp_Title")] NewHire newhire)
{
if (ModelState.IsValid)
{
_entities.NewHires.Add(newhire);
_entities.SaveChanges();
MailMessage mail = new MailMessage();
mail.To.Add("Stephen.Michaels#brixmor.com");
mail.From = new MailAddress("someone#somewhere.com");
mail.Subject = "Test";
string Body = "<a href=http://www.google.com>" + "Click for Record" + "</a>";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "test";
smtp.Port = 25;
smtp.Send(mail);
return RedirectToAction("NewHire");
}
return View(newhire);
}
I would suggest you to use the Url.Action
if (ModelState.IsValid)
{
_entities.NewHires.Add(newhire);
_entities.SaveChanges();
string url = Url.Action("ActionName", "ControllerName", newhire.id);
MailMessage mail = new MailMessage();
mail.To.Add("Stephen.Michaels#brixmor.com");
mail.From = new MailAddress("someone#somewhere.com");
mail.Subject = "Test";
string Body = "<a href='"+ url +"'>" + "Click for Record" + "</a>";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "test";
smtp.Port = 25;
smtp.Send(mail);
return RedirectToAction("NewHire");
}

The component cannot be found. (Exception from HRESULT: 0x88982F50) when setting stream to bitmapimage in windows phone 8 app

I am trying to add an element in existing isolated folder in xml
code:
public void writeToXML(List<AppTile> appList)
{
// Write to the Isolated Storage
XmlWriterSettings x_W_Settings = new XmlWriterSettings();
x_W_Settings.Indent = true;
using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!ISF.FileExists("config.xml"))
{
using (IsolatedStorageFileStream stream = ISF.OpenFile("config.xml", FileMode.CreateNew))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<AppTile>));
using (XmlWriter xmlWriter = XmlWriter.Create(stream, x_W_Settings))
{
serializer.Serialize(xmlWriter, appList);
}
stream.Close();
}
}
else
{
string tileName = null;
string url = null;
string key = null;
byte [] tilePic = null;
XDocument loadedData;
if (appList != null)
{
foreach (AppTile app in appList)
{
tileName = app.TileName;
url = app.Url;
key = app.Key;
tilePic = app.TilePic;
// tilePic = Encoding.UTF8.GetString(app.TilePic,0,app.TilePic.Length);
// tilePic = Encoding.Unicode.GetString(app.TilePic,0,app.TilePic.Length);
// var writer = new BinaryWriter(tilePic);
}
using (Stream stream = ISF.OpenFile("config.xml", FileMode.Open, FileAccess.ReadWrite))
{
loadedData = XDocument.Load(stream);
var RootNode = new XElement("AppTile");
RootNode.Add(new XElement("TileName", tileName));
RootNode.Add(new XElement("Key", key));
RootNode.Add(new XElement("Url", url));
RootNode.Add(new XElement("TilePic", tilePic));
// Find Root Element And Descedents and Append New Node After That
var root = loadedData.Element("ArrayOfAppTile");
var rows = root.Descendants("AppTile");
var lastRow = rows.Last();
lastRow.AddAfterSelf(RootNode);
}
// Save To ISOconfig.xml File
using (IsolatedStorageFileStream newStream = new IsolatedStorageFileStream("config.xml", FileMode.Create, ISF))
{
loadedData.Save(newStream);
newStream.Close();
}
}
}
}
}
while reading from xml i am using xmlWriter and deserialize it to get List
when ever i am trying to acces the tilePic of AppTile type i am getting error :The component cannot be found. with the following code::
Image img = new Image();
MemoryStream imgStream = new MemoryStream(NewApp.TilePic);//NewApp is AppTile type
BitmapImage imgSource = new BitmapImage();
imgSource.SetSource(imgStream);//here i get error
img.Source = imgSource;
Its most likely with the TilePic i am saving is not formatted correctly to be retrieved.
Please Help!!
Why don't you use the SaveJpeg extension methodoogy in creating the byte array?
This one might help you!
Windows Phone - byte array to BitmapImage converter throws exception
solved the issue:
while saving the byte array it is encoded to some format not recognizable while reading,So what i have done is saved it as a string.So the updated code is:
else
{
string tileName = null;
string url = null;
string key = null;
string tilePicString = null;
XDocument loadedData;
System.Windows.Media.Imaging.BitmapImage imgSource = new System.Windows.Media.Imaging.BitmapImage();
if (appList != null)
{
foreach (AppTile app in appList)
{
tileName = app.TileName;
url = app.Url;
key = app.Key;
//changed here
tilePicString = System.Convert.ToBase64String(app.TilePic);
}
//same code as above

subscription in reporting services

I want to subscribe report on specific schedule in reporting services 2008. i.e report will dilever to user automatically on schedule. I am using visual studio 2008. I have done the configuration setting (rsreportserver.config, app.config after adding refrences of asmx files) by refrence msdn. The code is running fine (no exception occur) and I also get subscription id through calling create subscription indicate all going fine. But after running the code no entry made in Subscription table of ReportServer database. And also not get any mail. While through report server web tool, I can get email and also entery made in database but not from coe. Please someone help me. What I am missing. Plz help
Code is given follow: (Keep in mind, I am using VS2008)
void SendReportEmail()
{
RSServiceReference.ReportingService2005SoapClient rs=new RSServiceReference.ReportingService2005SoapClient();
rs.ClientCredentials.Windows.AllowedImpersonationLevel = new System.Security.Principal.TokenImpersonationLevel();
string batchID = string.Empty;
RSServiceReference.ServerInfoHeader infoHeader = rs.CreateBatch(out batchID);
BatchHeader bh = new BatchHeader()
{
BatchID = batchID,
AnyAttr = infoHeader.AnyAttr
};
string report = "/PCMSR6Reports/PaymentRequestStatusMIS";
string desc = "Send email from code to Hisham#comsoft.com";
string eventType = "TimedSubscription";
string scheduleXml="<ScheduleDefinition xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><StartDateTime xmlns=\"http://schemas.microsoft.com/sqlserver/2006/03/15/reporting/reportingservices\">2010-03-06T15:15:00.000+05:00</StartDateTime></ScheduleDefinition>";
RSServiceReference.ParameterValue[] extensionParams = new RSServiceReference.ParameterValue[7];
extensionParams[0] = new RSServiceReference.ParameterValue();
extensionParams[0].Name = "TO";
extensionParams[0].Value = "Hisham#comsoft.com";
extensionParams[1] = new RSServiceReference.ParameterValue();
extensionParams[1].Name = "IncludeReport";
extensionParams[1].Value = "True";
extensionParams[2] = new RSServiceReference.ParameterValue();
extensionParams[2].Name = "RenderFormat";
extensionParams[2].Value = "MHTML";
extensionParams[3] = new RSServiceReference.ParameterValue();
extensionParams[3].Name = "Subject";
extensionParams[3].Value = "#ReportName was executed at #ExecutionTime";
extensionParams[4] = new RSServiceReference.ParameterValue();
extensionParams[4].Name = "Comment";
extensionParams[4].Value = "Here is your test report for testing purpose";
extensionParams[5] = new RSServiceReference.ParameterValue();
extensionParams[5].Name = "IncludeLink";
extensionParams[5].Value = "True";
extensionParams[6] = new RSServiceReference.ParameterValue();
extensionParams[6].Name = "Priority";
extensionParams[6].Value = "NORMAL";
RSServiceReference.ParameterValue[] parameters = new RSServiceReference.ParameterValue[10];
parameters[0] = new RSServiceReference.ParameterValue();
parameters[0].Name = "BranchId";
parameters[0].Value = "1";
parameters[1] = new RSServiceReference.ParameterValue();
parameters[1].Name = "UserName";
parameters[1].Value = "admin";
parameters[2] = new RSServiceReference.ParameterValue();
parameters[2].Name = "SupplierId";
parameters[2].Value = "0";
string matchData = scheduleXml;
RSServiceReference.ExtensionSettings extSettings = new RSServiceReference.ExtensionSettings();
extSettings.ParameterValues = extensionParams;
extSettings.Extension = "Report Server Email";
try
{
string sub="";
RSServiceReference.ServerInfoHeader SubID = rs.CreateSubscription(bh, report, extSettings, desc, eventType, matchData, parameters, out sub);
rs.FireEvent(bh, "TimedSubscription", sub);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
Detail response will be highly appricated.
Try adding # at the beginning of your xml string #"