Java mail getInputStream left recipient - inputstream

i'm writing a mail send method with javamail.
I can not understand why I get and error as: Recipient not set.
This is my code:
public static void sendMail(String to, String subj, String body, String attachmentName, byte[] attachment, String mime) throws Exception {
Properties p = System.getProperties();
Session session = Session.getInstance(p);
MimeMessage dummyMessage = new MimeMessage(session);
dummyMessage.setFrom(new InternetAddress(LovProvider.getOpzioni().get("mail.address")));
dummyMessage.setSubject(subj);
String[] tos = to.split(";");
Address[] tosAddr = new InternetAddress[tos.length];
for (int i = 0; i < tos.length; i++) {
tosAddr[i] = new InternetAddress(tos[i]);
}
dummyMessage.setRecipients(Message.RecipientType.TO, tosAddr);
Multipart mp = new MimeMultipart();
MimeBodyPart bp = new MimeBodyPart();
bp.setText(body);
mp.addBodyPart(bp);
if (attachmentName != null && attachment != null) {
DataSource dataSource = new ByteArrayDataSource(attachment, mime);
MimeBodyPart attachBodyPart = new MimeBodyPart();
attachBodyPart.setDataHandler(new DataHandler(dataSource));
attachBodyPart.setFileName(attachmentName);
mp.addBodyPart(attachBodyPart);
}
dummyMessage.setContent(mp);
//***** DEBUGGING here I find the recipient
sendMail(dummyMessage.getInputStream());
}
public static void sendMail(InputStream emlFile) throws Exception {
Properties props = System.getProperties();
props.put("mail.host", LovProvider.getOpzioni().get("mail.out.host"));
props.put("mail.transport.protocol", LovProvider.getOpzioni().get("mail.out.protocol"));
props.put("mail." + LovProvider.getOpzioni().get("mail.out.protocol") + ".port", LovProvider.getOpzioni().get("mail.out.port"));
Session mailSession = Session.getDefaultInstance(props, PasswordAuthentication.getAuth(LovProvider.getOpzioni().get("mail.out.user"), LovProvider.getOpzioni().get("mail.out.password")));
MimeMessage message = new MimeMessage(mailSession, emlFile);
//***** DEBUGGING here I CAN NOT find the recipient
Transport.send(message);
}
As I wrote in comments in debug mode i can see the recipient correctly set in the first part, whant i convert it to InputStream to the second method I can not find recipient anymore.

I can't debugging your code, but maybe this examples can help you:
Examples about sending/receiving mail via/from gmail
http://famulatus.com/component/search/?searchword=gmail&searchphrase=all&Itemid=9999

Related

Crystal report method not found

I made a feedback project. I made it on ASP.NET MVC 5 it also has crystal reports. reports were working fine, but suddenly they stopped to work. I don't what happened with them. but since last week I tried hard to find solution but unfortunately could not get the right one who solved the solution. I downloaded different run times but all went vain. this is the bottom line of error.
"Method not found: 'CrystalDecisions.ReportAppServer.DataDefModel.PropertyBag CrystalDecisions.ReportAppServer.ReportDefModel.ISCRExportOptions.get_ExportOptionsEx()'"
this is the code:
public CrystalReportFeedback UserFeedbackDateWise(FeedbackReport be){
if (Session["CurrentUser"] != null && Convert.ToInt32(Session["User_Id"]) != 0)
{
string reportPath = Path.Combine(Server.MapPath("~/Reports"), "UserFeedbackReport.rpt");
if (ModelState.IsValid)
{
be.FromDate = Convert.ToDateTime(TempData["UserFromDate"]);
be.ToDate = Convert.ToDateTime(TempData["UserToDate"]);
be.User_Id = Convert.ToInt32(Session["User_Id"]);
}
return new CrystalReportFeedback(reportPath, be);
}
else
{
return null;
//new CrystalReportFeedback(reportPath, be);
}
}
Init of the report :
public CrystalReportFeedback(string reportPath, FeedbackReport be)//, object dataSet)
{
//int[] array;
string strConnect = Convert.ToString(System.Configuration.ConfigurationManager.ConnectionStrings["TSC"]);
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(strConnect);
string _username = builder.UserID;
string _pass = builder.Password;
string _server = builder.DataSource;
string _database = builder.InitialCatalog;
ReportDocument reportDocument = new ReportDocument();
//
reportDocument.Load(reportPath);
reportDocument.SetDatabaseLogon(_username, _pass, _server, _database);
if (be.Region_Id != 0)
{
reportDocument.SetParameterValue("#Region_Id", be.Region_Id);
}
if (be.User_Id != 0)
{
reportDocument.SetParameterValue("#User_Id", be.User_Id);
}
reportDocument.SetParameterValue("#FromDate", be.FromDate);
reportDocument.SetParameterValue("#ToDate", be.ToDate);
//reportDocument.ExportToDisk(ExportFormatType.PortableDocFormat, "C:\report.pdf");
_contentBytes = StreamToBytes(reportDocument.ExportToStream(ExportFormatType.PortableDocFormat));
}
Export method :
public override void ExecuteResult(ControllerContext context)
{
var response = context.HttpContext.ApplicationInstance.Response;
response.Clear();
response.Buffer = false;
response.ClearContent();
response.ClearHeaders();
response.Cache.SetCacheability(HttpCacheability.Public);
response.ContentType = "application/pdf";
using (var stream = new MemoryStream(_contentBytes))
{
stream.WriteTo(response.OutputStream);
stream.Flush();
}
}
private static byte[] StreamToBytes(Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
Hope that I will get my solution at earliest.
this is modified code:
[HttpGet]
public FileResult UserFeedbackDateWise(FeedbackReport be)
{
if (Session["CurrentUser"] != null && Convert.ToInt32(Session["User_Id"]) != 0)
{
string reportPath = Path.Combine(Server.MapPath("~/Reports"), "UserFeedbackReport.rpt");
if (ModelState.IsValid)
{
be.FromDate = Convert.ToDateTime(TempData["UserFromDate"]);
be.ToDate = Convert.ToDateTime(TempData["UserToDate"]);
be.User_Id = Convert.ToInt32(Session["User_Id"]);
}
string strConnect = Convert.ToString(System.Configuration.ConfigurationManager.ConnectionStrings["TSC"]);
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(strConnect);
string _username = builder.UserID;
string _pass = builder.Password;
string _server = builder.DataSource;
string _database = builder.InitialCatalog;
ReportDocument reportDocument = new ReportDocument();
//
reportDocument.Load(reportPath);
reportDocument.SetDatabaseLogon(_username, _pass, _server, _database);
if (be.Region_Id != 0)
{
reportDocument.SetParameterValue("#Region_Id", be.Region_Id);
}
if (be.User_Id != 0)
{
reportDocument.SetParameterValue("#User_Id", be.User_Id);
}
reportDocument.SetParameterValue("#FromDate", be.FromDate);
reportDocument.SetParameterValue("#ToDate", be.ToDate);
Stream stream = reportDocument.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
//Here i have my stream with my pdf report, i just create a new FileStreamResult and return it to my client like that :
FileStreamResult myfile = new FileStreamResult(stream, "application/pdf");
return myfile;
//new CrystalReportFeedback(reportPath, be);
}
else
{
return null;
//new CrystalReportFeedback(reportPath, be);
}
}
This isn't a coding issue, it's a runtime issue. The version of the crystal runtime or the bitness of your application.
One thing to try first is to upgrade both your development version and ensure you're running the same version in production. See https://apps.support.sap.com/sap/support/knowledge/public/en/2148492 for more details
It says:
Compile your application either to 'X86 mode' or 'X64 mode'
Install the particular versions of runtimes on deployment machine.
i.e. If the application is compiled as 32 bit, then install the 32bit runtimes.
I'll try my best to help you exporting your report, but your post is not very clear. For your next post try to be very specific and provide as much information as you can.
I currently made a MVC project and export a crystalreport report from my controller to my client.
I think that your ExecuteResult method can work, but working with the httpcontext is useless, Crystalreport and .NET provide some useful methods to do the same.
So i'll show you how i create and export my report so you can copy / paste and modify your code.
Here is my controller method, called from a button :
[HttpGet]
public FileResult InitReport()
{
//I create my report here
FileImportReport rptH = new FileImportReport();
// Some configuration on the report, datasource, databaselogon .. etc
...
//
//Then I export my report to a pdf stream like that :
Stream stream = rptH.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
//Here i have my stream with my pdf report, i just create a new FileStreamResult and return it to my client like that :
FileStreamResult myfile = new FileStreamResult(stream, "application/pdf");
return myfile;
}
My method is called from a button but it can work like you want, or the file can be saved in any known path.
You can test to reproduce my code, in your CrystalReportFeedback method use my code with your reportDocument object, you don't need to use your StreamToBytes method.
Regards,
EDIT : Useful links with your error :
Crystal Reports exception in Visual Studio 2013
https://www.arcanadev.com/support/kb/K00000499.aspx

Updating Red5 SharedObject closing stream

I'm trying to create a voice conference room with all users can speak and use the mic. But as an Admin, I should have the privilege to mute any user. So, I add to the user an attribute for the mic which will be check in client side and enable/disable user's mic accordingly. The server side code looks like:
String identifier;
String userID;
private int _gId = 1;
private Map<String,Object> newUser;
#Override
public boolean appConnect(IConnection conn, Object[] params) {
identifier = (String)params[1];
userID = (String)params[0];
int _globalUserId = _gId++;
conn.getClient().setAttribute("id", _globalUserId);
newUser = new HashMap<String,Object>();
newUser.put("identifier", (String)params[0]);
newUser.put("mic", 1); //mic value to be checked in client side
return true;
}
#Override
public boolean roomJoin(IClient client, IScope scope) {
ISharedObject so = getSharedObject(scope, "users_so");
so.setAttribute(userID,newUser);
return true;
}
#SuppressWarnings("unchecked")
public void muteUser(String userID){
IScope scope = Red5.getConnectionLocal().getScope();
ISharedObject so = getSharedObject(scope, "users_so");
Map<String,Object> user= new HashMap<String,Object>();
user = (Map<String, Object>) so.getAttribute(userID);
if(user != null){
user.put("mic", 0);
so.beginUpdate();
boolean removed = so.removeAttribute(userID);
boolean updated = so.setAttribute(userID,user);
so.endUpdate();
log.info("Mic: " + user.get("mic"));
log.info("Removed: " + removed);
log.info("Updated: " + updated);
}
}
The problem arises when I try to call the muteUser method. Red5 says that the stream is closed. I think this happens when I remove the attribute of the user and added it again but I couldn't find another way to update the sharedObject's mic value.
Does any one have a better idea to update a sharedObject without losing stream?
The SO that you're requesting doesn't work like a user map that it would appear you think it does in your example. I would suggest storing a map in the SO and then do a get / add to the map; the map in this case being shared, so you'd have to make it thread-safe; I'd use a ConcurrentMap there like so:
ISharedObject so = getSharedObject(scope, "users_so");
if (so == null) {
// make sure your so exists
}
so.beginUpdate();
ConcurrentMap<String, Object> users = (ConcurrentMap<String, Object>) so.getAttribute("users");
if (users == null) {
users = new ConcurrentHashMap<String, Object>();
so.setAttribute("users" users);
}
Object user = users.get(userID);
user.put("mic", 0);
so.endUpdate();

Jetty Filter to modify the Response - java.lang.IllegalStateException: WRITER

I am trying to modify the http response in a filter and am getting the following exception
java.lang.IllegalStateException: WRITER at
org.eclipse.jetty.server.Response.getOutputStream(Response.java:657)
at
javax.servlet.ServletResponseWrapper.getOutputStream(ServletResponseWrapper.java:142)
at
org.eclipse.jetty.servlets.ProxyServlet.service(ProxyServlet.java:414)
at
org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:643)
at
org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1331)
at
com.cisco.vsx.node.proxy.http.RegexFilter.doFilter(RegexFilter.java:36)
I am using SelectChannelSelector and ProxyServlet.Transparent proxy.
Below is the snippet from test class
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
ProxyServlet.Transparent p1 = new ProxyServlet.Transparent("/proxy",
"www.cisco.com", 80);
ServletHolder servletHolder = new ServletHolder(p1);
context.addServlet(servletHolder, "/proxy/*");
context.addFilter(new FilterHolder(RegexFilter.class), "/*", null);
server.setHandler(context);
server.start();
server.join();
This is the code from filter class
PrintWriter out = response.getWriter();
CharResponseWrapper wrapper = new CharResponseWrapper((HttpServletResponse) response);
chain.doFilter(request, wrapper);
String html = wrapper.toString();
if (regex != null && response.getContentType() != null
&& response.getContentType().startsWith("text/html")) {
Matcher matcher = regex.matcher(html);
Map<Integer, Integer> matches = new LinkedHashMap<Integer, Integer>();
while (matcher.find()) {
int start = matcher.start(1);
System.out.println("START" + start);
int end = matcher.end(1);
System.out.println("END" + end);
matches.put(start, end - start);
}
StringBuffer sb = new StringBuffer();
int start = 0;
for (int startIndex : matches.keySet()) {
String str = html.substring(start, startIndex) + "/proxy/";
sb.append(str);
start = startIndex + matches.get(startIndex);
}
html = sb.toString();
}
response.setContentLength(html.getBytes().length);
out.write(html);
Not sure where stuff is going wrong.
Your Jetty Response can be in two (technically three) distinct modes. One is the writer mode, the other one is the streaming mode (and the third one is basically the undecided mode).
If you call getWriter() on an 'undecided' response, you're putting it in writer mode, which can't be reversed. If something later tries to use this response in streaming mode (by calling getOutputStream()) the Exception you see is thrown.
To fix this, don't use this response in writer mode and 'do your thing' on the OutputStream instead. If you were accessing the writer at a later point (after doChain), you'd get the inverse Exception
java.lang.IllegalStateException: STREAM
instead.

How to Pass custom objects using Spring's REST Template

I have a requirement to pass a custom object using RESTTemplate to my REST service.
RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, Object> requestMap = new LinkedMultiValueMap<String, Object>();
...
requestMap.add("file1", new FileSystemResource(..);
requestMap.add("Content-Type","text/html");
requestMap.add("accept", "text/html");
requestMap.add("myobject",new CustomObject()); // This is not working
System.out.println("Before Posting Request........");
restTemplate.postForLocation(url, requestMap);//Posting the data.
System.out.println("Request has been executed........");
I'm not able to add my custom object to MultiValueMap. Request generation is getting failed.
Can someone helps me to find a way for this? I can simply pass a string object without problem.User defined objects makes the problem.
Appreciate any help !!!
You can do it fairly simply with Jackson.
Here is what I wrote for a Post of a simple POJO.
#XmlRootElement(name="newobject")
#JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class NewObject{
private String stuff;
public String getStuff(){
return this.stuff;
}
public void setStuff(String stuff){
this.stuff = stuff;
}
}
....
//make the object
NewObject obj = new NewObject();
obj.setStuff("stuff");
//set your headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
//set your entity to send
HttpEntity entity = new HttpEntity(obj,headers);
// send it!
ResponseEntity<String> out = restTemplate.exchange("url", HttpMethod.POST, entity
, String.class);
The link above should tell you how to set it up if needed. Its a pretty good tutorial.
To receive NewObject in RestController
#PostMapping("/create") public ResponseEntity<String> createNewObject(#RequestBody NewObject newObject) { // do your stuff}
you can try this
public int insertParametro(Parametros parametro) throws LlamadasWSBOException {
String metodo = "insertParam";
String URL_WS = URL_WS_BASE + metodo;
Integer request = null;
try {
logger.info("URL_WS: " + URL_WS);
request = restTemplate.postForObject(URL_WS, parametro, Integer.class);
} catch (RestClientResponseException rre) {
logger.error("RestClientResponseException insertParametro [WS BO]: " + rre.getResponseBodyAsString());
logger.error("RestClientResponseException insertParametro [WS BO]: ", rre);
throw new CallWSBOException(rre.getResponseBodyAsString());
} catch (Exception e) {
logger.error("Exception insertParametro[WS BO]: ", e);
throw new CallWSBOException(e.getMessage());
}
return request;
}

Send Email From Amazon SES in ASP.NET MVC App

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);
}

Resources