I'm using Lotus Domino.dll. Already finished sending. How set delivery options to DeliveryPriority=H and DeliveryReport=C?
CODE
NotesSession _notesSession = new NotesSession();
NotesDocument _notesDocument = null;
string sMailFile = "mail/" + login + ".nsf";
_notesSession.Initialize(passwrod);
NotesDatabase _notesDataBase = _notesSession.GetDatabase(sServerName, sMailFile, false);
if (!_notesDataBase.IsOpen)
{
_notesDataBase.Open();
}
_notesDocument = _notesDataBase.CreateDocument();
_notesDocument.ReplaceItemValue("Form", "Memo");
_notesDocument.ReplaceItemValue("SendTo", aSendTo);
_notesDocument.ReplaceItemValue("Subject", aSubject);
NotesRichTextItem _richTextItem = _notesDocument.CreateRichTextItem("Body");
_richTextItem.AppendText(text + "\r\n");
_richTextItem.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, "", file);
var oItemValue = _notesDocument.GetItemValue("SendTo");
_notesDocument.SaveMessageOnSend = true;
_notesDocument.Send(false, ref oItemValue);
Add the lines
_notesDocument.ReplaceItemValue("DeliveryPriority", "H");
_notesDocument.ReplaceItemValue("DeliveryReport", "C");
after your Subject line.
You can find a complete list of mail options here.
Related
I have an intranet site to manage clients' communications. There are only a few controls: a textbox for the Subject, Attachment (fileUpload control), and a multiline textbox for the content of the email.
Using the fileUpload control, I select the pdf file that I want to send to clients. All the details about the clients (name, email address, etc) is coming from a sql table.
The sending works just fine, it sends the email with the attachment. However, the PDF attachment cannot be opened. The error is that the file hasn't been correctly decoded. I am not sure where the problem is. Does anyone have an idea on where the problem is?
Here is the code (for the sending procedure):
protected void BtnSendAcctClientsEmail_Click(object sender, EventArgs e)
{
if (uplAcctngAttachment.HasFile)
{
HttpPostedFile uploadedFile = uplAcctngAttachment.PostedFile;
if (IsAcctngFileHeaderValid(uploadedFile))
{
var fileName = Path.GetFileName(uplAcctngAttachment.PostedFile.FileName);
string strExtension = Path.GetExtension(fileName);
if (strExtension != ".pdf")
{
lblAcctngFileErr.Text = "Please attach pdf files only.";
return;
}
else
{
lblAcctngFileErr.Text = "";
}
try
{
DataSet ds_Emails = new DataSet();
constr = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
cn = new SqlConnection(constr);
cmd = new SqlCommand("getAcctClientsEmailAddresses", cn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da_Emails = new SqlDataAdapter(cmd);
cn.Open();
da_Emails.Fill(ds_Emails);
cn.Close();
for (int vLoop = 0; vLoop < ds_Emails.Tables[0].Rows.Count; vLoop++)
{
string name_first = ds_Emails.Tables[0].Rows[vLoop]["contact_fname"].ToString();
email = ds_Emails.Tables[0].Rows[vLoop]["email"].ToString();
client_id = ds_Emails.Tables[0].Rows[vLoop]["id"].ToString();
clientType = "acctng";
// Build the Body of the message using name_first into a string and then send mail.
//send e-mail
string fromAddress = "associates#example.com";
string ccAddress = fromAddress;
string subject = txtAcctngSubject.Text;
string sendEmail = "Dear " + name_first + "," + Environment.NewLine + Environment.NewLine + txtAcctngMessage.Text;
sendEmail += Environment.NewLine + Environment.NewLine + "Go to https://www.example.com/crm_removal.aspx?id=" + client_id +
"&type=" + clientType + " to be removed from any future communications.";
MailAddress fromAdd = new MailAddress(fromAddress, "Associates");
MailAddress toAdd = new MailAddress(email);
MailMessage eMailmsg = new MailMessage(fromAdd, toAdd);
Attachment attachment;
attachment = new Attachment(uplAcctngAttachment.PostedFile.InputStream, fileName);
eMailmsg.Subject = subject;
eMailmsg.Attachments.Add(attachment);
eMailmsg.Body = sendEmail;
SmtpClient client = new SmtpClient();
client.Send(eMailmsg);
}
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "')</script>");
sendingErr = ex.Message;
SendErr();
}
Response.Redirect("default.aspx", false);
}
}
}
private bool IsAcctngFileHeaderValid(HttpPostedFile uploadedFile)
{
Stream s = uplAcctngAttachment.PostedFile.InputStream;
StringBuilder buffer = new StringBuilder();
int value;
for (int i = 0; i < 2; i++)
{
value = s.ReadByte();
if (value == -1)
{
throw new Exception("Invalid file data.");
}
buffer.Append(value.ToString());
}
/*extension code list for files
* 7780 = exe
* 8075 = docx
* 3780 = pdf
* 7173 = gif
* 255216 = jpg
* 13780 = png
* 6677 = bmp
* 208207 =xls, doc, ppt
* 8075 = xlsx,zip,pptx,mmap,zip
* 8297 = rar
* 01 = accdb,mdb
*/
string[] input = { "208207", "8075", "3780", "255216", "13780", "6677" };
List<string> headers = new List<string>(input);
return headers.Contains(buffer.ToString());
}
When you pass the stream to the Attachment constructor it's offset by 2 bytes because you read from it earlier in IsAcctngFileHeaderValid corrupting the data.
Reset the stream position using uplAcctngAttachment.PostedFile.InputStream.Position = 0; when IsAcctngFileHeaderValid is done reading.
I tried searching something here but nothing seems to fit my need.
I created an SSIS package that runs a report -> Attaches it to an email and send it to a bunch of people, many times (different recipients, different files).
Due to Zapier limitations I can't create a FreshDesk ticket with attachments and that is for me a must to have so I'm exploring FreshDesk API, but I'm no c# developer.
I found some examples online and now I'm trying to fit this code:
FreshSamples C-Sharp Create Ticket with attachment into my existing code, hoping to pass all my variable as ticket fields '
#region VSTA generated code
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
public void Main()
{
// initialize StreamReader class for text file
StreamReader streamReader = new StreamReader(Dts.Variables["User::MHTMailPath"].Value.ToString());
// Read the StreamReader To End and assign to local variable
string StreamText = streamReader.ReadToEnd();
// assign SSIS variable with value of StreamText local variable.
this.Dts.Variables["User::HTMLMail"].Value = StreamText;
// TODO: Add your code here
MailMessage email = new MailMessage();
if ((Dts.Variables["User::MHTEmail1"].Value.ToString() != null) && (Dts.Variables["User::MHTEmail1"].Value.ToString() != string.Empty))
{
email.To.Add(Dts.Variables["User::MHTEmail1"].Value.ToString());
}
if ((Dts.Variables["User::MHTEmail2"].Value.ToString() != null) && (Dts.Variables["User::MHTEmail2"].Value.ToString() != string.Empty))
{
email.To.Add(Dts.Variables["User::MHTEmail2"].Value.ToString());
}
if ((Dts.Variables["User::MHTEmail3"].Value.ToString() != null) && (Dts.Variables["User::MHTEmail3"].Value.ToString() != string.Empty))
{
email.To.Add(Dts.Variables["User::MHTEmail3"].Value.ToString());
}
if ((Dts.Variables["User::MHTEmail4"].Value.ToString() != null) && (Dts.Variables["User::MHTEmail4"].Value.ToString() != string.Empty))
{
email.To.Add(Dts.Variables["User::MHTEmail4"].Value.ToString());
}
//email.CC.Add(CCAddresses);
email.From = new MailAddress("xxx#xxx.com");
email.Subject = Dts.Variables["User::MHTCd"].Value.ToString() + " - " + Dts.Variables["User::MHTCustomerDS"].Value.ToString() + " R" + Dts.Variables["User::Period"].Value.ToString().Trim().Substring(Dts.Variables["User::Period"].Value.ToString().Trim().Length - 2, 2);
email.IsBodyHtml = true;
email.Body = Dts.Variables["User::HTMLMail"].Value.ToString();
string reportFile = Dts.Variables["User::ReportFile"].Value.ToString();
try
{
//For MHT file. Decode MHTML to HTML and embed in email body
if (Path.GetExtension(reportFile) == ".mht")
{
var decodedHtml = new StringBuilder();
using (var reader = new StreamReader(reportFile))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (line != "Content-Transfer-Encoding: base64") continue;
reader.ReadLine();
while ((line = reader.ReadLine()) != String.Empty)
if (line != null)
decodedHtml.Append(
Encoding.UTF8.GetString(
Convert.FromBase64String(line)));
break;
}
}
email.Body = email.Body + Environment.NewLine + decodedHtml.ToString();
email.IsBodyHtml = true;
}
else
{
//Attach the file
Attachment attachmentFile = new Attachment(reportFile);
email.Attachments.Add(attachmentFile);
}
}
catch (Exception e)
{
Dts.Events.FireError(0, "create email message", e.Message, String.Empty, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
//System.Diagnostics.Process proc = new System.Diagnostics.Process();
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
smtpClient.EnableSsl = true;
smtpClient.Credentials = new System.Net.NetworkCredential("xxx#xxx.com", "xxxxxxx");
System.Diagnostics.Process proc = new System.Diagnostics.Process();
try
{
smtpClient.Send(email);
//email.Attachments.Dispose();
//File.Delete(reportFile);
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception e)
{
Dts.Events.FireError(0, "smtp emailing", e.Message, String.Empty, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
finally
{
if (email != null)
{
email.Dispose();
}
if (smtpClient != null)
{
//smtpClient.Dispose();
}
}
Dts.TaskResult = (int)ScriptResults.Success;
}
}
but I'm losing my mind trying to get my reportFile to be correctly "taken" by FreshDesk sample which expects a file on the filesystem. Moreover, I will need to attach more that one file so I was wondering if any good samaritan would point me in the right direction.
Thanks in advance
Ren
It will be okay to call email.Attachments.Add() multiple times to add multiple attachments:
The key part is :
To turn an existing file into an attachment:
Attachment attachmentFile = new Attachment(reportFile);
email.Attachments.Add(attachmentFile);
To turn a string block into an attachment:
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))
{
writer.Write(reportFile);
writer.Flush();
stream.Position = 0;
email.Attachments.Add(new Attachment(stream, "myreport-xyz.txt", "text/plain"));
}
I wrote following method to send emails
public ActionResult SendEmail(UserData user)
{
try
{
#region Email content
MailMessage m = new MailMessage(
new MailAddress("sender#email.com", "Represent Location"),
new MailAddress(Reciever_Email));
m.Subject = "Mail Topic";
m.IsBodyHtml = true;
m.Body = string.Format("<img src=\"##IMAGE##\" alt=\"\"><BR/><BR/>Hi " + user.FirstName + "," + "<BR/><BR/>Your account has been successfully created with the Comp. Please click on the link below to access your account.<BR/><BR/>" + "Username - " + user.UserName + "<BR/>" + "Password - " + user.Password + "<BR/><BR/>" + "Please click here to Activate your account", user.UserName, Url.Action("ConfirmEmail", "Account", new { Token = user.Id, Email = user.UserEmail }, Request.Url.Scheme)) + string.Format("<BR/><BR/>Regards,<BR/>The Human Resource Department <BR/>");
// create the INLINE attachment
string attachmentPath = System.Web.HttpContext.Current.Server.MapPath("~/Images/logo.jpg");
// generate the contentID string using the datetime
string contentID = Path.GetFileName(attachmentPath).Replace(".", "") + "#zofm";
Attachment inline = new Attachment(attachmentPath);
inline.ContentDisposition.Inline = true;
inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
inline.ContentId = contentID;
inline.ContentType.MediaType = "image/png";
inline.ContentType.Name = Path.GetFileName(attachmentPath);
m.Attachments.Add(inline);
// replace the tag with the correct content ID
m.Body = m.Body.Replace("##IMAGE##", "cid:" + contentID);
SmtpClient smtp = new SmtpClient("Email_Server_IP");
smtp.Port = ServerPort;
smtp.Credentials = new NetworkCredential("sender#email.com", "sender_password");
smtp.EnableSsl = false;
smtp.Send(m);
#endregion
return View(user);
}
catch (Exception ex)
{
throw ex;
}
}
then I'm accessing above method in main controller like following
// Email Sending
UserData sampleData = new UserData();
sampleData.Id = user.Id;
sampleData.UserName = user.UserName;
sampleData.UserEmail = user.Email;
sampleData.FirstName = user.FirstName;
sampleData.Password = model.Password;
// await EmailController.Sendemail(sampleData);
var emailCntrl = new EmailController();
var sendEmail = emailCntrl.SendEmail(sampleData);
this is compiling without any compile times errors. but when I debug this I can see
in this line m.Body = str... I can see a error like this
because of that I'm getting an exception
Message = "Object reference not set to an instance of an object."
How can I solve this
You don't have Request, because you create just EmailController class. When controller factory creates controller for request it passes request data to Controller.Initialize Method.
Of course the best practice is to create EmailService as was mentioned above, but as answer for your question, you can make workaround. You can pass RequestContext of parent controller to EmailController in constructor and call Initialize. It's going to look like.
public EmailController()
{
}
public EmailController(RequestContext requestContext)
{
base.Initialize(requestContext);
}
And in your controller
var emailCntrl = new EmailController(this.ControllerContext.RequestContext);
var sendEmail = emailCntrl.SendEmail(sampleData);
You can also just set the ControllerContext
var emailCntrl = new EmailController(){ControllerContext = this.ControllerContext};
var sendEmail = emailCntrl.SendEmail(sampleData);
Well given that there was no request added to controller before calling action, it would be null.
There is no need for a controller there just to send the email.
Create a class/service to handle the email and pass in any dependencies
public class EmailService {
public UserData SendEmail(UserData user, string confirmationEmailUrl) {
try
{
#region Email content
MailMessage m = new MailMessage(
new MailAddress("sender#email.com", "Represent Location"),
new MailAddress(Reciever_Email));
m.Subject = "Mail Topic";
m.IsBodyHtml = true;
m.Body = string.Format("<img src=\"##IMAGE##\" alt=\"\"><BR/><BR/>Hi " + user.FirstName + "," + "<BR/><BR/>Your account has been successfully created. Please click on the link below to access your account.<BR/><BR/>" + "Username - " + user.UserName + "<BR/>" + "Password - " + user.Password + "<BR/><BR/>" + "Please click here to Activate your account", user.UserName, confirmationEmailUrl + string.Format("<BR/><BR/>Regards,<BR/>The Human Resource Department <BR/>");
// create the INLINE attachment
string attachmentPath = System.Web.HttpContext.Current.Server.MapPath("~/Images/logo.jpg");
// generate the contentID string using the datetime
string contentID = Path.GetFileName(attachmentPath).Replace(".", "") + "#zofm";
Attachment inline = new Attachment(attachmentPath);
inline.ContentDisposition.Inline = true;
inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
inline.ContentId = contentID;
inline.ContentType.MediaType = "image/png";
inline.ContentType.Name = Path.GetFileName(attachmentPath);
m.Attachments.Add(inline);
// replace the tag with the correct content ID
m.Body = m.Body.Replace("##IMAGE##", "cid:" + contentID);
SmtpClient smtp = new SmtpClient("Email_Server_IP");
smtp.Port = ServerPort;
smtp.Credentials = new NetworkCredential("sender#email.com", "sender_password");
smtp.EnableSsl = false;
smtp.Send(m);
#endregion
return user;
}
catch (Exception ex)
{
throw ex;
}
}
}
And get the action from main controller
// Email Sending
UserData sampleData = new UserData();
sampleData.Id = user.Id;
sampleData.UserName = user.UserName;
sampleData.UserEmail = user.Email;
sampleData.FirstName = user.FirstName;
sampleData.Password = model.Password;
var confirmationEmailUrl = Url.Link("Default", new { Action = "ConfirmEmail", Controller = "Account", Token = sampleData.Id, Email = sampleData.UserEmail });
var emailService = new EmailService();
var user = emailService.SendEmail(sampleData, confirmationEmailUrl);
im creating .doc file and sending mail. in pc dowloaded file from
attachment is opening properly but in mobile its not opening
properly. only html tags are displaying in smart phones.can u
tell me how to render this .doc file so that in mobile also attached
file can be displayed ?
attached file is not supporting in smartphones .only html tags are
displaying.
can anyone tell in my code how to use docX library in my code?
protected void btnMail_Click(object sender, EventArgs e)
{
DisplayProgressBar();
Response.Clear();
try
{
if (Session["Projectname"] != null && Session["Projectname"].ToString() != string.Empty)
{
string Projname = Session["Projectname"].ToString();
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
design.RenderControl(htmlWrite);
string strBuilder = stringWrite.ToString();
string strPath = Request.PhysicalApplicationPath + "\\Temp\\WeeklyReport of " + Projname + ".doc";
LblNoteMsg.Text = strPath;
//code changed to send mails
if (File.Exists(strPath))
{
var counter = 1;
strPath = strPath.Replace(".doc", " (" + counter + ").doc");
while (File.Exists(strPath))
{
strPath = strPath.Replace("(" + counter + ").doc", "(" + (counter + 1) + ").doc");
counter++;
}
}
using (var fStream = File.Create(strPath))
{
fStream.Close();
fStream.Dispose();
}
using(StreamWriter sWriter = new StreamWriter(strPath))
{
sWriter.Write(strBuilder);
sWriter.Close();
sWriter.Dispose();
Response.Clear();
}
DateTime input = DateTime.Now;
int delta = DayOfWeek.Monday - input.DayOfWeek;
DateTime dats = DateTime.Now.AddDays(delta);
//this week
DateTime monday = input.AddDays(delta);
string MonDate = monday.ToShortDateString();
DateTime sat = monday.AddDays(5);
string SatDate = sat.ToShortDateString();
StreamReader r = new StreamReader(Server.MapPath("~/WeeklyMail.txt"));
string body = r.ReadToEnd();
MailMessage Msg = new MailMessage();
string MailId = txtMailId.Text;
foreach (string ss in MailId.Split(",".ToCharArray()))
{
if (string.IsNullOrEmpty(ss) == false)
{
Msg.To.Add(new MailAddress(ss));
}
}
Msg.Bcc.Add(new MailAddress("support#sunlightit.com"));
body = body.Replace("<%MonDate%>", MonDate);
body = body.Replace("<%SatDate%>", SatDate);
Msg.Subject = "Weekly status Report of " + Projname + "," + DateTime.Now.ToShortDateString() + "";
Msg.Body = body;
Msg.IsBodyHtml = true;
Msg.Attachments.Add(new Attachment(strPath));
SmtpClient MailServer = new SmtpClient();
try
{
MailServer.Send(Msg);
string reply = (Msg.DeliveryNotificationOptions = System.Net.Mail.DeliveryNotificationOptions.OnSuccess).ToString();
if (reply == "OnSuccess")
{
txtMailId.Text = "";
tblMail.Visible = false;
lblMsg.ForeColor = System.Drawing.Color.Green;
lblMsg.Text = "Mail has send succesfully";
}
else
{
lblMsg.ForeColor = System.Drawing.Color.Red;
lblMsg.Text = "Mail delivery unsuccessfull";
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
if (ex.InnerException != null)
{
Console.WriteLine("InnerException is: {0}", ex.InnerException);
}
}
}
else
{
Response.Redirect("~/Login.aspx");
}
}
catch (Exception)
{
ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "clentscript", "alert('It is being used by another process.Please Try after sometime ');", true);
}
}
You did not make a proper .doc file. A .doc file is not composed of HTML. Word on your computer does know HTML so it will open the file, but likely the program you're using on the mobile devices will just treat it as a corrupted .doc file.
Instead, you should build a proper Word document. There's plenty of libraries for generating .docx Open Office XML Document (Word 2007) files. Find one that works for you needs, and use it.
Write the file on the server path and pass the link to user make the download:
Example:
http://yourapp.com/files/download/051651203210.doc
I am trying to use this code to get changes in a site collection. But i don't know how to get the databaseId.
SiteData.SiteData siteData = new SiteData.SiteData();
siteData.UseDefaultCredentials = true;
siteData.Url = "http://localhost:333/_vti_bin/sitedata.asmx";
string lastChangeID = String.Empty;
string result = siteData.GetContent(SiteData.ObjectType.SiteCollection, "", "", "", false, false, ref lastChangeID);
XmlDocument doc = new XmlDocument();
doc.LoadXml(result);
string startChangeId = string.Empty;
string endChangeId = doc.ChildNodes[0].ChildNodes[0].Attributes["ChangeId"].Value;
bool moreChanges;
string databaseId = "";
string result2 = siteData.GetChanges(SiteData.ObjectType.SiteCollection, databaseId, ref startChangeId, ref endChangeId, 5, out moreChanges);
MessageBox.Show(result2);
Thank you for your time.
Edit:
This is the GetContent Result:
You can call the siteData.GetContent method again, this time with the ContentDatabase as ObjectType. The returning CAML should contain the ContentDatabaseId.
string s = siteData.GetContent(SiteData.ObjectType.ContentDatabase, "", "", "", false, false, ref lastChangeID);
You don't need the database Id for calling "GetChanges" method on SiteCollection scope. I use "GetChangesEx" and it works well, this method returns similar information to "GetChanges". Check the protocol specification (PDF) to see the differences: Site Data protocol specification. Also, I think your problem with the "SoapServerException" is the same I had here: other question.
This code example is on the other question I mentioned, but I'll post it here for better readability:
SiteData.SiteDataSoapClient siteDataService = new SiteData.SiteDataSoapClient();
siteDataService.Endpoint.Address = new System.ServiceModel.EndpointAddress("URL/_vti_bin/sitedata.asmx");
siteDataService.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential("username", "password", "domain");
siteDataService.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
String xmlInput = "<GetChanges>" +
"<ObjectType>7</ObjectType>" +
"<ContentDatabaseId/>" +
"<StartChangeId>1;1;69b025ce-96a7-4131-adc0-7da1603e8d24;634439727021700000;47404</StartChangeId>" +
"<EndChangeId>1;1;69b025ce-96a7-4131-adc0-7da1603e8d24;634441802456970000;47472</EndChangeId>" +
"<RequestLoad>100</RequestLoad>" +
"<GetMetadata>False</GetMetadata>" +
"<IgnoreSecurityIfInherit>True</IgnoreSecurityIfInherit>" +
"</GetChanges>";
String result = siteDataService.GetChangesEx(1, xmlInput);