sending mail through controller (using gmail) - asp.net-mvc-5

So, first time attempting to send mail from a mvc application and lo and behold, it didn't work :(
Here's the spaghetti I've whipped up so far from some sources, needless to say I end up in the Error View:
[HttpPost]
public ActionResult Contact(Contact c)
{
if (ModelState.IsValid)
{
try
{
MailMessage msg = new MailMessage();
SmtpClient smtp = new SmtpClient();
MailAddress from = new MailAddress(c.Email.ToString());
StringBuilder sb = new StringBuilder();
msg.To.Add("myaddress#mail.com");
msg.Subject = "New Message";
msg.IsBodyHtml = false;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Credentials = new System.Net.NetworkCredential("myaddress#mail.com", "mypassword");
sb.Append("Name: " + c.Name);
sb.Append(Environment.NewLine);
sb.Append("Email: " + c.Email);
sb.Append(Environment.NewLine);
sb.Append("Message: " + c.Message);
msg.Body = sb.ToString();
smtp.Send(msg);
msg.Dispose();
return View();
}
catch (Exception)
{
return View("Error");
}
}
return View();
}

Related

How to send a mail notification using C# code

I have used the below code to send the mail notifications using the C# code
public static void SendNotification(string filepath)
{
try
{
SmtpClient mailServer = new SmtpClient(ConfigurationManager.AppSettings["host"], int.Parse(ConfigurationManager.AppSettings["portnumber"]));
mailServer.EnableSsl = true;
mailServer.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["sender_username"], ConfigurationManager.AppSettings["sender_password"]);
string from = ConfigurationManager.AppSettings["sender"];
string to = ConfigurationManager.AppSettings["receipients"];
string cc = ConfigurationManager.AppSettings["receipientCC"];
MailMessage msg = new MailMessage(from, to);
msg.Subject = "Branch API Export Results";
msg.Body = "Test Mail. Please Find Attached for the Results from Branch API Export";
msg.CC.Add(cc);
msg.Attachments.Add(new Attachment(filepath));
mailServer.Send(msg);
}
catch (Exception ex)
{
//Log
}
}
Included the configuration values in the App.Config. Any better way other than this.
Here is.
private static void SendMail(string subject, string content)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("YOURMAİL");
mail.To.Add("MAİLTO");
mail.Subject = subject;
mail.Body = content;
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("YOURMAİL", "YOURMAİLPASSWORD");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
catch (Exception ex)
{
}
}
This is simplest way to send mail. Don't forget to add using System.Net.Mail;

Uploading file from code error “File Not found”

I m uploading file to Sharepoint online dcoument librar from byte array and on execution getting error "File Not found"
public static bool UploadFile(SP sp, string folderName, string fileNameWithExtension, byte[] fileContent, TraceWriter log)
{
bool result = false;
try
{
SecureString securePwd = new SecureString();
char[] pwdarray = sp.pwd.ToCharArray();
foreach (var item in pwdarray)
{
securePwd.AppendChar(item);
}
SharePointOnlineCredentials creds = new SharePointOnlineCredentials(sp.id, securePwd);
using (ClientContext clientContext = new ClientContext(sp.url))
{
log.Info("UploadToSharePoint 1");
clientContext.Credentials = creds;
clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
Web web = clientContext.Web;
var fileCreationInformation = new FileCreationInformation();
fileCreationInformation.Content = fileContent;
fileCreationInformation.Overwrite = true;
fileCreationInformation.Url = fileNameWithExtension;
Microsoft.SharePoint.Client.List docs = web.Lists.GetByTitle("All Attachments");
docs.RootFolder.Folders.Add(folderName);
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(fileCreationInformation);
clientContext.ExecuteQuery();
return result = true;
}
}
catch (Exception ex)
{
throw ex;
}
}
Please help spent 2 days but not finding a solution :(
Below sample code works for me.
using (var context = new ClientContext("https://domain.sharepoint.com/sites/Developer"))
{
Console.ForegroundColor = ConsoleColor.Green;
string password = "pw";
SecureString sec_pass = new SecureString();
Array.ForEach(password.ToArray(), sec_pass.AppendChar);
sec_pass.MakeReadOnly();
context.Credentials = new SharePointOnlineCredentials("lee#domain.onmicrosoft.com", sec_pass);
string fileName = "C:\\Lee\\test.docx";
FileStream stream = System.IO.File.OpenRead(fileName);
byte[] fileBytes = new byte[stream.Length];
stream.Read(fileBytes, 0, fileBytes.Length);
stream.Close();
var fileCreationInformation = new FileCreationInformation();
fileCreationInformation.Content = fileBytes;
fileCreationInformation.Overwrite = true;
fileCreationInformation.Url = "test.docx";
Microsoft.SharePoint.Client.List docs = context.Web.Lists.GetByTitle("MyDoc3");
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(fileCreationInformation);
context.ExecuteQuery();
Console.WriteLine("done");
Console.ReadKey();
}

Send DataSet data email via attachment Excel File xls ( Not Creating Excel File ) C#

I want to send DataSet data with email excel file attachment in C# but I don't want to create Excel file physically. It can be do with MemoryStream but I couldn't.
Another problem I want to set Excel file's encoding type because data may be Russian or Turkish special character.
Please help me...
Here is my sample code...
<!-- language: c# -->
var response = HttpContext.Response;
response.Clear();
response.Charset = "utf-8";
response.ContentEncoding = System.Text.Encoding.Default;
GridView excelGridView = new GridView();
excelGridView.DataSource = InfoDataSet;
excelGridView.DataBind();
excelStringWriter = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(excelStringWriter);
excelGridView.RenderControl(htw);
byte[] ExcelData = emailEncoding.GetBytes(excelStringWriter.ToString());
MemoryStream ms = new MemoryStream(ExcelData);
mailMessage.Attachments.Add(new Attachment(ms, excelFileName, "application/ms-excel"));
<!-- language: c# -->
here is another one simple and easy with excel attchment
public string SendMail(string LastId)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
SqlCommand cmd = new SqlCommand("sp_GetMailData", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#LastID", LastId);
con.Open();
string result = "0";
string temptext = "";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
//ExportToSpreadsheet(dt,"My sheet");
GridView gv = new GridView();
gv.DataSource = dt;
gv.DataBind();
AttachandSend(gv);
con.Close();
return result.ToString();
}
public void AttachandSend(GridView gv)
{
StringWriter stw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(stw);
gv.RenderControl(hw);
System.Text.Encoding Enc = System.Text.Encoding.ASCII;
byte[] mBArray = Enc.GetBytes(stw.ToString());
System.IO.MemoryStream mAtt = new System.IO.MemoryStream(mBArray, false);
System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
MailAddress address = new
MailAddress("xxxxxxxxxxxxx", "Admin");
mailMessage.Attachments.Add(new Attachment(mAtt, "sales.xls"));
mailMessage.Body = "Hi PFA";
mailMessage.From = address;
mailMessage.To.Add("xxxxxxxxxxxx");
mailMessage.Subject = "xxxxxxxxxxxxxx";
mailMessage.IsBodyHtml = true;
var smtp = new SmtpClient();
smtp.Send(mailMessage);
}
Here is your solution
private static Stream DataTableToStream(DataTable table)
{
const string semiColon = ";";
var ms = new MemoryStream();
var sw = new StreamWriter(ms);
foreach (DataColumn column in table.Columns)
{
sw.Write(column.ColumnName);
sw.Write(semiColon);
}
sw.Write(Environment.NewLine);
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
sw.Write(row[i].ToString().Replace(semiColon, string.Empty));
sw.Write(semiColon);
}
sw.Write(Environment.NewLine);
}
return ms;
}
private static MailMessage CreateMail(string from,
string to,
string subject,
string body,
string attname,
Stream tableStream)
{
// using System.Net.Mail
var mailMsg = new MailMessage(from, to, subject, body);
tableStream.Position = 0;
mailMsg.Attachments.Add(
new Attachment(tableStream, attname, CsvContentType));
return mailMsg;
}
private const string CsvContentType = "application/ms-excel";
private static void ExportToSpreadsheetInternal(Stream tableStream, string name)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.ContentType = CsvContentType;
context.Response.AppendHeader(
"Content-Disposition"
, "attachment; filename=" + name + ".xls");
tableStream.Position = 0;
tableStream.CopyTo(context.Response.OutputStream);
context.Response.End();
}
public static void ExportToSpreadsheet(DataTable table, string name)
{
var stream = DataTableToStream(table);
var mailMsg = CreateMail("from#ddd.com",
"to#ddd.com",
"spread",
"the spread",
name,
stream);
//ExportToSpreadsheetInternal(stream, name);
// send the mailMsg with SmtpClient (config in your web.config)
var smtp = new SmtpClient();
smtp.Send(mailMsg);
}
Call this method
ExportToSpreadsheet(DataTable table, string name)

POI not sending xls file as attachment , sending as string

one of my junior code is not sending excel file as attachment . It is sending file like
------=_Part_0_2066339629.1374147892060
Content-Type: text/plain; name="Service_Change_Alert_Thu Jul 18 17:14:50 IST 2013.xlsx"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="Service_Change_Alert_Thu Jul 18 17:14:50 IST 2013.xlsx"
UEsDBBQACAAIANqJ8kIAAAAAAAAAAAAAAAARAAAAZG9jUHJvcHMvY29yZS54bWytkV1LwzAUhu/7
K0Lu2yTr1BHaDlEGguLADsW7kB7bYvNBEu3892bdrCheennyPu/D4aRY79WA3sH53ugSs4xiBFqa
ptdtiXf1Jl3hdZUkhTQOts5YcKEHj2JL+xJ3IVhOiJcdKOGzGOuYvBinRIija4kV8lW0QBaUnhMF
QTQiCHKwpXbW4aOPS/vvykbOSvvmhknQSAIDKNDBE5Yx8s0GcMr/WZiSmdz7fqbGcczGfOLiRow8
3d0+TMunvfZBaAm4ShAqTnYuHYgADYoOHj4slPgrecyvrusNrhaU5Sm9SNmqZowvl/yMPhfkV//k
function is following
public void sendSeviceabilityMail(List<OctpinSaveBean> datalist)
throws MessagingException {
Session session = null;
Map<String, String> utilsMap = ApplicationBean.utilsProperties;
if (utilsMap == null || utilsMap.size() == 0)
utilsMap = ApplicationBean.getUtilsPropertyFileValues();
smtpHost = utilsMap.get("SMTPHost");
to = utilsMap.get("To");
try {
if (smtpHost != null && to != null) {
Date date = new Date();
XSSFWorkbook updateDataBook =
updatedServiceabilityExcel(datalist);
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpHost);
props.put("To", to);
session = Session.getInstance(props, null);
String str = "strstr";
Multipart multipart = new MimeMultipart();
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setContent(str, "text/html");
BodyPart messageBodyPart = new MimeBodyPart();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
updateDataBook.write(baos);
byte[] bytes = baos.toByteArray();
DataSource ds = new ByteArrayDataSource(bytes,
"application/vnd.ms-excel");
DataHandler dh = new DataHandler(ds);
messageBodyPart.setDataHandler(dh);
String fileName = "Service_Change_Alert_" + date+".xlsx";
messageBodyPart.setFileName(fileName);
messageBodyPart.setHeader("Content-disposition", "attachment;
filename=\"" + fileName + "\"");
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart);
if (to != null && to.length() > 0) {
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("tech_noida
<tech_noida#xyz.com>"));
String[] toArray = to.split(",");
InternetAddress[] address = new
InternetAddress[toArray.length];
for (int i = 0; i < toArray.length; i++) {
address[i] = new InternetAddress(toArray[i]);
}
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("Updated Serviceability Alert!!!");
msg.setContent(multipart);
msg.setSentDate(date);
try {
Transport.send(msg);
logger.info("Mail has been sent about the updated serviceability alert to :" + to);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
The problem is not related to POI, but with JavaMail (plus the way different email clients handles the specs and malformed emails). Try this:
Multipart multipart = new MimeMultipart();
MimeBodyPart html = new MimeBodyPart();
// Use actual html not "strstr"
html.setContent("<html><body><h1>Hi</h1></body></html>", "text/html");
multipart.addBodyPart(html);
// ...
// Joop Eggen suggestion to avoid spaces in the file name
String fileName = "Service_Change_Alert_"
+ new SimpleDateFormat("yyyy-MM-dd_HH:mm").format(date) + ".xlsx";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
updateDataBook.write(baos);
byte[] poiBytes = baos.toByteArray();
// Can be followed by the DataSource / DataHandler stuff if you really need it
MimeBodyPart attachment = new MimeBodyPart();
attachment.setFileName(filename);
attachment.setContent(poiBytes, "application/vnd.ms-excel");
//attachment.setDataHandler(dh);
attachment.setDisposition(MimeBodyPart.ATTACHMENT);
multipart.addBodyPart(attachment);
Update:
Also don't forget to call saveChanges to update the headers before sending the message.
msg.saveChanges();
See this answer for further details.

Groovy Tcp client/server sending maps

I created a basic tcp client and server in groovy and I'm wanting to send maps from the server to the client, I'm wondering if I'm able send maps across and still being able to access the values.
//TCP Server
def book1 = [Title of Book: "Groovy Recipes", Author: "Scott Davis", Number of Pages: "241"]
server = new ServerSocket(2000)
println("Waiting for connection")
while(true) {
server.accept() { socket ->
socket.withStreams { input, output ->
w = new BufferedWriter(new OutputStreamWriter(output))
String message = "Connection was successful"
r = new BufferedReader(new InputStreamReader(input))
while(true) {
if(message != null) {
w.writeLine(message)
w.flush()
message = null
}
String a = r.readLine()
if(a=="book1") {
message = book1
} else {
message = "$a command unknown."
sendMessage(message)
println message
message = null
}
}
}
}
}
def sendMessage(String msg) {
try {
w.writeLine(msg)
w.flush();
} catch(IOException ioException) {
ioException.printStackTrace();
}
}
Here is my Client (where I'm wanting to receive the map and get the values)
//TCP Client
def grabBookInfo {
queryData()
}
public void queryData() {
def hosts = ["localhost"]
for(int aHost = 0; aHost < hosts.size; aHost++) {
bookClient(hosts[aHost]);
}
}
public void bookClient() {
def commands = ["book1"]
def answers = [commands.size]
def requestSocket = new Socket(host, 2000)
r = new BufferedReader(new InputStreamReader(requestSocket.getInputStream()));
w = new BufferedWriter(new OutputStreamWriter(requestSocket.getOutputStream()));
String message = "Connection was successful"
message = r.readLine()
println("Server>" + message)
for(int n = 0; n < commands.size; n++) {
sendMessage(commands[n]);
answers[n] = r.readLine()
}
//get map values here
//answers[0] = Book
//println Book.['Title of Book']
//println Book.['Author']
//println Book.['Number of Pages']
w.flush()
w.close()
}
public void sendMessage(msg) {
w.write(msg+"\r\n");
w.flush();
System.out.println("client>" + msg);
}
}
Am I on the right track?
In the server, use ObjectOutputStream.
In the client use ObjectInputStream.
Server:
private static final HashMap<String, Integer> TEST_MAP;
static {
TEST_MAP = new HashMap<String, Integer>();
TEST_MAP.put("one", 1);
TEST_MAP.put("two", 2);
}
...
ServerSocket ss = new ServerSocket(port);
Socket socket = ss.accept();
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
out.writeObject(TEST_MAP);
out.close();
Client:
Socket socket = new Socket(HOST, PORT);
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
Object o = in.readObject();
assert o instanceof HashMap<?, ?>;
#SuppressWarnings("unchecked")
HashMap<String, Integer> m = (HashMap<String, Integer>)o;
assertTrue(m.get("one") == 1);
assertTrue(m.get("two") == 2);
in.close();
socket.close();
Serialize the maps, example
http://www.java2s.com/Tutorial/Java/0140__Collections/SerializingHashMaps.htm

Resources