I am trying to give the looks of email like this:
This is the looks of my email
Where Right hand side of the email subject is Ignou logo and it is a jpg image.
I have the following class for sending the email and it is working fine:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Net.Configuration;
using System.Net.Mail;
namespace ProductManagementweb.HelperClasses
{
public class SendEmail
{
public static int SendMail(string ReceiverAddress, string Recsubject, string Recbody)
{
try
{
System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
MailSettingsSectionGroup settings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");
System.Net.NetworkCredential credential = new System.Net.NetworkCredential(settings.Smtp.Network.UserName, settings.Smtp.Network.Password);
//Create the SMTP Client
SmtpClient client = new SmtpClient();
client.Host = settings.Smtp.Network.Host;
client.Credentials = credential;
client.Timeout = 30000;
client.EnableSsl = true;
MailMessage mm = new MailMessage();
mm.From = new MailAddress(settings.Smtp.Network.UserName, "Support Team (Clique City)");
mm.To.Add(ReceiverAddress);
mm.Priority = MailPriority.High;
// Assign the MailMessage's properties
mm.Subject = Recsubject;
mm.Body = Recbody;
mm.IsBodyHtml = false;
client.Send(mm);
return 1;
}
catch (Exception ex)
{
throw ex;
}
}
}
}
How can i give the email Format like the image above it is sure that i have to mention the format using html tags but i am unknown where i have to mention and how. therefore any help will surely be appreciated.
You should put the html content from your email design in Recbody i.e. email body and change
mm.IsBodyHtml = false;
to
mm.IsBodyHtml = true;
In addition to vivekd's asnwer.
You just need to build the HTML in the code e.g
string messageContent = "";
messageContent += "<table><tr><td>" + telephoneNumber + "</td><td>" + locationAddress + "</td></tr></table>"
Then set the
mm.IsBodyHtml = true;
And sent the email content to be the messageContent
mm.Body = messageContent;
Obviously you will need to design the layout of the email yourself and build it up by appending to the messageContent string.
Related
I'm trying to print a server report without preview using C#. The report is printing fine in WidowsXP but it's printing in zoomed view in Windows 7 and Windows 10. Below is my code.
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Reporting.WinForms;
namespace Dahlawi.ManPower.Recruiting.Forms
{
public partial class FrmReportViewer1 : Form
{
List<Metafile> m_ReportPages = new List<Metafile>();
int m_ReportPageIndex = 0;
public FrmReportViewer1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
PrintDocument objPrintDoc = new PrintDocument();
objPrintDoc.PrintPage += PrintPageHandler;
PrintDialog objPrintDiag = new PrintDialog();
objPrintDiag.Document = objPrintDoc;
DialogResult objDiagResult = default(DialogResult);
objDiagResult = objPrintDiag.ShowDialog();
if (objDiagResult == DialogResult.OK)
{
objPrintDoc.PrinterSettings = objPrintDiag.PrinterSettings;
this.m_ReportPages = new List<Metafile>();
this.m_ReportPageIndex = 0;
this.reportViewer.ShowCredentialPrompts = false;
this.reportViewer.ServerReport.ReportServerCredentials.NetworkCredentials = new System.Net.NetworkCredential("USER", "PASSWORD", "DOMAIN");
this.reportViewer.ServerReport.ReportServerUrl = new Uri("http://SERVER/ReportServer");
this.reportViewer.ServerReport.ReportPath = "/DMR/Candidate_Information";
ReportParameter[] reportParameters = new ReportParameter[] { new ReportParameter("CandidateId", "16744") };
reportParameters[0].Visible = false;
this.reportViewer.ServerReport.SetParameters(reportParameters);
this.reportViewer.RefreshReport();
string deviceInfo = "<DeviceInfo>" + "<OutputFormat>emf</OutputFormat>" + " <PageWidth>8.5in</PageWidth>" + " <PageHeight>11in</PageHeight>" + " <MarginTop>0.2in</MarginTop>" + " <MarginLeft>0.5in</MarginLeft>" + " <MarginRight>0.5in</MarginRight>" + " <MarginBottom>0.2in</MarginBottom>" + "</DeviceInfo>";
Warning[] objWarnings = null;
string[] sStreamIDs = null;
string sMimeType = "";
string sEncoding = "";
string sFilenameExtension = "";
byte[] renderedPage = null;
renderedPage = this.reportViewer.ServerReport.Render("Image", deviceInfo, out sMimeType, out sEncoding, out sFilenameExtension, out sStreamIDs, out objWarnings);
this.m_ReportPages.Add(new Metafile(new MemoryStream(renderedPage)));
foreach (string sStreamId in sStreamIDs)
{
renderedPage = this.reportViewer.ServerReport.RenderStream("Image", sStreamId, deviceInfo, out sMimeType, out sEncoding);
this.m_ReportPages.Add(new Metafile(new MemoryStream(renderedPage)));
}
objPrintDoc.Print();
objPrintDoc = null;
}
}
private void PrintPageHandler(object sender, PrintPageEventArgs e)
{
if (this.m_ReportPageIndex < this.m_ReportPages.Count)
{
Metafile imgPage = this.m_ReportPages[this.m_ReportPageIndex];
this.m_ReportPageIndex += 1;
e.Graphics.DrawImage(imgPage, 0, 0, imgPage.Width, imgPage.Height);
e.HasMorePages = this.m_ReportPageIndex < this.m_ReportPages.Count;
}
}
}
}
When I print the report using above code in WindowsXP it prints like this Proper Print
But when I run the same code in Windows 7 or Windows 10 it prints like this Zoomed Print
Please help me run this code on Windows 7 / Windows 10. I can provide more details if required.
I found out the issue and it's the "emf" output format which is causing the problem on Windows 7 and Windows 10 but working fine on Windows XP / Windows 2003. I changed the output format in "deviceInfo" string from "emf" to "jpg" (other formats e.g. "png", "jpeg", "bmp" also work fine) and then I changed the type of "m_ReportPages" list object from "Metafile" to "Image" and got the issue resolved.
Im tyring to send an email with my program to an gmx email. Every time I try to send the mail I get the same error message in my console.
What can be the solution for that?
The error message:
System.Net.Mail.SmtpException: SMTP server requiers secure connection or the client wasnt authenticated. server response was: authentication required.
in - System.Net.Mail.SendMailAsyncResult.End(IAsyncResult result)
in - System.Net.Mail.SmtpClient.SendMailCallback(IAsyncResult result)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;
using System.ComponentModel;
namespace SMTP_Client
{
class Program
{
static bool mailSent = false;
private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
// Get the unique identifier for this asynchronous operation.
String token = (string)e.UserState;
if (e.Cancelled)
{
Console.WriteLine("[{0}] Send canceled.", token);
}
if (e.Error != null)
{
Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
}
else
{
Console.WriteLine("Message sent.");
}
mailSent = true;
}
public static void Main(string[] args)
{
SmtpClient client = new SmtpClient("smtp.gmx.com",25);
MailAddress from = new MailAddress("example#project.com", "me " + (char)0xD8 + " you", System.Text.Encoding.UTF8);
MailAddress to = new MailAddress("example#gmx.com");
MailMessage message = new MailMessage(from, to);
message.Body = "The project has succeeded ";
message.Subject = "made it!";
client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
string userState = "test message2\n";
client.SendAsync(message, userState);
Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
string answer = Console.ReadLine();
if (answer.StartsWith("c") && mailSent == false)
{
client.SendAsyncCancel();
}
message.Dispose();
Console.WriteLine("proccess ended.");
}
}
}
I have to get html response from another website and load to my application. I written below code,
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
namespace MVC_TEST.Controllers
{
public class DocumentCloudController : Controller
{
public string Index()
{
var result = GetResponse();
return result;
}
private static string GetResponse()
{
var html = string.Empty;
const string url = #"http://localhost/xxxxx/yyyyy/logon.aspx";
var request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
if (stream != null)
{
using (var reader = new StreamReader(stream))
{
html = reader.ReadToEnd();
}
}
}
}
return html;
}}
}
}
Controls are loaded properly, But image, css and js path is mapped to relative path
/xxxx/yyyy/dojo.js ,
/xxxx/style/logon.css,
/xxxx/images/logon.png
in html, here i have to change that to actual url like below
http://localhost/xxxx/yyyy/dojo.js ,
http://localhost/xxxx/style/logon.js ,
http://localhost/xxxx/images/logon.png
One option is find these content in html replace that.
Is there any other option to change url dynamically ?
Is IIS URL Rewrite module will suitable for my requirement ?
Please share your thoughts
Using IIS URL Rewrite Module could work but I would recommend using a HTML parser like HTML Agility Pack or AngleSharp to query and manipulate the DOM.
The example below is a snippet that worked for me when creating a reverse proxy:
foreach (var link in document.DocumentNode.SelectNodes("//link[#href]"))
{
var orgHrefValue = link.GetAttributeValue("href", string.Empty);
var updHrefValue = string.Concat("[BASE URL]", GetAbsoluteUrlString(requestedUrl, orgHrefValue).AbsoluteUri);
link.SetAttributeValue("href", updHrefValue);
}
private static Uri GetAbsoluteUrlString(string baseUrl, string url)
{
var uri = new Uri(url, UriKind.RelativeOrAbsolute);
if (!uri.IsAbsoluteUri)
uri = new Uri(new Uri(baseUrl), uri);
return uri;
}
I'm trying to use HTMLUnit to get the javascript elements on a webpage (https://www.coursera.org/courses), and it is only loading the html data. How do I get it to display the information shown in the javascript container?
Thanks!
My current code:
public String DownloadPage(String str){
final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3_6);
webClient.getOptions().setTimeout(20000);
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setThrowExceptionOnScriptError(false);
try{
HtmlPage page = webClient.getPage(str);
XmlPage page2 = webClient.getPage(str);
int n = webClient.waitForBackgroundJavaScript(100000);
System.out.println("Executing " + n + " JavaSript jobs!");
System.out.println("OUTPUT: " + page2);
System.out.println("OUTPUT: " + page.asXml());
webClient.closeAllWindows();
}
catch(IOException e){
JOptionPane.showMessageDialog(null, "error");
}
webClient.closeAllWindows();
return "";
}
use
String theContent1 = webClient.getPage(theURL).getWebResponse().getContentAsString();
instead of
String theContent2 = webClient.getPage(theURL);
theContent1 should contain the actual page source including JavaScripts (if any).
I am using C# and the Exchange Web Services API and have been unable to find a way to retrieve a contact using the extended property named Account. We have used this field to hold an integer number that is meaningful to an in-house developed system. Under WebDAV, we knew how to retrieve the Contact but need some help (hopefully a short example or code snippet) to demonstrate how to do this.
I have used extended property with appointments, so maybe they work on the same concept as the contacts.
The Idea is to put a Guid for appointments as their native IDs are not constant.
private static readonly PropertyDefinitionBase AppointementIdPropertyDefinition = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.PublicStrings, "AppointmentID", MapiPropertyType.String);
public static PropertySet PropertySet = new PropertySet(BasePropertySet.FirstClassProperties, AppointementIdPropertyDefinition);
//Setting the property for the appointment
public static void SetGuidForAppointement(Appointment appointment)
{
try
{
appointment.SetExtendedProperty((ExtendedPropertyDefinition)AppointementIdPropertyDefinition, Guid.NewGuid().ToString());
appointment.Update(ConflictResolutionMode.AlwaysOverwrite, SendInvitationsOrCancellationsMode.SendToNone);
}
catch (Exception ex)
{
// logging the exception
}
}
//Getting the property for the appointment
public static string GetGuidForAppointement(Appointment appointment)
{
var result = "";
try
{
appointment.Load(PropertySet);
foreach (var extendedProperty in appointment.ExtendedProperties)
{
if (extendedProperty.PropertyDefinition.Name == "AppointmentID")
{
result = extendedProperty.Value.ToString();
}
}
}
catch (Exception ex)
{
// logging the exception
}
return result;
}
Not sure if you still need this... but I just solved something close myself:
My answer here should be in the ballpark of what you want. I'm using a boolean as well as Account here:
ExchangeService service = this.GetService(); // my method to build service
FolderId folderID = GetPublicFolderID(service, "My Address Book");
ContactsFolder folder = ContactsFolder.Bind(service, folderID);
int folderCount = folder.TotalCount;
var guid = DefaultExtendedPropertySet.PublicStrings;
var epdAccount = new ExtendedPropertyDefinition(0x3A00, MapiPropertyType.String);
var epdCID = new ExtendedPropertyDefinition(0x3A4A, MapiPropertyType.String);
var epdCBLN = new ExtendedPropertyDefinition(guid, "CustomBln", MapiPropertyType.Boolean);
var epdCDBL = new ExtendedPropertyDefinition(guid, "CustomDbl", MapiPropertyType.Double);
var view = new ItemView(folderCount);
view.PropertySet = new PropertySet(BasePropertySet.FirstClassProperties);
view.PropertySet.Add(epdAccount);
view.PropertySet.Add(epdCID);
view.PropertySet.Add(epdCBLN);
view.PropertySet.Add(epdCDBL);
//var searchOrFilterCollection = new List<SearchFilter>();
//searchOrFilterCollection.Add(new SearchFilter.IsEqualTo(epdCBLN, true));
//searchOrFilterCollection.Add(new SearchFilter.IsEqualTo(epdAccount, "user"));
//var filter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchOrFilterCollection);
var filter = new SearchFilter.IsEqualTo(epdAccount, "user");
var contacts = service.FindItems(folderID, filter, view);
foreach (Contact contact in contacts)
{
string Account;
int CID;
bool CBLN;
double CDBL;
contact.GetLoadedPropertyDefinitions();
contact.TryGetProperty(epdAccuont, out Account);
contact.TryGetProperty(epdCID, out CID);
contact.TryGetProperty(epdCBLN, out CBLN);
contact.TryGetProperty(epdCDBL, out CDBL);
Console.WriteLine(String.Format("{0, -20} - {1} - {2} - {3} - {4}"
, contact.DisplayName
, contact.EmailAddresses[EmailAddressKey.EmailAddress1]
, Account
, CID
, CBLN
, CDBL
));
}